502 Bad Gateway – Nginx, uWSGI, and Django in Separate Docker Containers

dockernginxuwsgi

Im having a little difficulty determining why nginx and uwsgi arent working to serve my django app. Here is the problem from the nginx log.

    nginx-01: 2015/12/06 07:47:50 [error] 10#0: *1 connect() failed (111: Connection refused) while connecting to upstream, 
client: xxx.xxx.xxx.xxx, server: , request: "GET / HTTP/1.1", upstream: "uwsgi://0.0.0.0:8001", host: "54.252.197.191"

So uwsgi and django reside in one container with the following file settings.

[uwsgi]
http-socket = :8001
chdir = %dsrc/myproject/
env = DJANGO_SETTINGS_MODULE=myproject.settings
module = myproject.wsgi:application
master = true
processes = 4

My docker file starts up uwsgi and i expose port 8001 to the host

CMD ["uwsgi", "uwsgi.ini"]

My second container which is for nginx has the following nginx virtualhost settings.

upstream uwsgi_django {
    server 0.0.0.0:8001;
}

server {
    listen 80;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location / {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
        uwsgi_pass uwsgi_django;
        include /etc/nginx/uwsgi_params;
    }

    location = /favicon.ico {
      log_not_found off;
    }
}

Here are my containers from docker ps.

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES                                       
16f181bafb61        ccbf828a3ab2        "nginx -g 'daemon off"   7 minutes ago       Up 7 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx-container                             
33d4d5d17ca3        65ad56e6756c        "uwsgi uwsgi.ini"        13 minutes ago      Up 13 minutes       0.0.0.0:8001->8001/tcp                     django-container                            
688f4b0f9e29        postgres            "/docker-entrypoint.s"   7 hours ago         Up About an hour    0.0.0.0:5432->5432/tcp                     postgres-container   

If i curl 0.0.0.0:8001 from the host machine i get back the welcome page for django project. However if i try and view it from the browser i get a 502 bad gateway error (which in my eyes seems link ive set up uwsgi correctly but there is some issue between nginx communicating with uwsgi.

Best Answer

Here is your problem:

upstream uwsgi_django {
    server 0.0.0.0:8001;
}

This only "works" if the processes are in the same host, VM or container, because it tries to make a connection to the same machine. When they are in different containers, it does not work.

You need to alter your nginx configuration so that it uses the internal IP address of the uwsgi container. How you do this depends on how you are creating your containers, which you didn't specify. Check the relevant documentation.