1

I've been setting a simple docker-compose for a Django application, in which I have 3 containers: the Django app, a Postgres container, and NGINX. I successfully set up both Django and Postgres and tested connecting directly to their containers, so now the only thing left was to set up NGINX on the docker-compose file. I used the following NGINX default.conf file, from another template repository:

upstream django {
  server app:8000;
}

server {
  listen 80;
  server_name localhost;

  location / {
    try_files $uri @proxy_to_app;
  }

  location @proxy_to_app {
    proxy_pass http://django;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }

  location /static/ {
      autoindex on;
      alias /static/;
  }

  location /media/ {
      autoindex on;
      alias /media/;
  }
}

And this was my docker-compose file:

version: "2"
services:
  nginx:
    image: nginx:latest
    container_name: NGINX
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./test:/djangoapp/test
      - ./config/nginx:/etc/nginx/conf.d
      - ./test/static:/static
    depends_on:
      - app
  app:
    build: .
    container_name: DJANGO
    command: bash -c "./wait-for-it.sh db:5432 && python manage.py makemigrations && python manage.py migrate && gunicorn test.wsgi -b 0.0.0.0:8000"
    depends_on:
      - db
    volumes:
      - ./djangoapp/test:/djangoapp/test
      - ./test/static:/static
    expose:
      - "8000"
    env_file:
      - ./config/djangoapp.env
  db:
    image: postgres:latest
    container_name: POSTGRES
    env_file:
      - ./config/database.env

But for some reason I wasn't able to connect on the Django app at all via localhost:80 (the browser always threw me a 502 error, and the container wasn't logging anything when I tried). After a lot of troubleshooting, I found out that the offending line was proxy_set_header Host $host;, and commenting it out made me successfully connect to the Django app via localhost. So the problem was that my NGINX configuration had to use the proxy_host variable instead.

The problem is that I have no idea why that happened in the first place, because looking at this other question (Nginx: when to use proxy_set_header Host $host vs $proxy_host), I was suppose to use $host to proxy from my Django application, and other NGINX configuration examples also sets up the Host like that.

I may be missing something as NGINX is a tad bit confusing for me, but I don't understand why I wasn't able to connect and NGINX wasn't logging anything before I commented that line.

0 Answers0