Docker + Django if_debug template tag is not working

I am running a docker-compose with nginx routing requests to my Django server, with this config:

upstream django {
    server backend:8000;
}

server {

    listen 80;

    location / {
        proxy_pass http://django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

To use the {% if debug %} template tag I know I need both the correct internal IP and the DEBUG setting turned on. I get the correct internal IPs by running the following code snippet in my Django settings.py:

import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS = [ip for ip in ips] + ['127.0.0.1']

When I docker exec -it backend sh, and import the DEBUG and INTERNAL_IPS settings, I get that the values are ['172.19.0.4', '127.0.0.1'] and True, respectively. Then, when I run docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) to check the containers' IP address, I see that the backend container that runs Django has an IP of 172.19.0.4, same as the internal IP.

Despite this all, in the Django template, I get a Django debug mode error (further proving that debug is turned on) that says that an error got triggered on line 61!!!

57    {% if debug %}
58    <!-- This url will be different for each type of app. Point it to your main js file. -->
59    <script type="module" src="http://frontend:3000/src/main.jsx"></script>
60    {% else %}
61    {% render_vite_bundle %}
62    {% endif %}

Can someone help me understand what I'm doing wrong and why this template tag won't work? Is there an easier way to do an if statement based on the Django debug setting? Thanks in advance!

I figured it out! I was getting the IP of the backend container when I typed hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()), but what I really wanted was to mark Nginx's forwarding as "internal". So, I changed the line to hostname, _, ips = socket.gethostbyname_ex("nginx") and the request got forwarded correctly. Might be worth it to consider whitelisting all of the DOcker containers' internal IPs so we can receive messages freely.

Back to Top