[Solved]-Django-gunicorn-nginx: 502 bad gateway

13đź‘Ť

First. Don’t use if in an nginx conf. It’s bad. Like really, really horrible. Use the following instead:

location / {
    try_files $uri @proxy;
}

location @proxy {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server_djangoapp;
}

See: http://wiki.nginx.org/IfIsEvil and http://wiki.nginx.org/Pitfalls

Now, as far as debugging goes. Your gunicorn workers are booting because there’s some fatal error. Try shutting down gunicorn. If you’re using supervisor:

sudo supervisorctl stop [gunicorn process name]

Then, from your project root run:

python manage.py run_gunicorn -c path/to/gunicorn.conf

Note any startup errors or if it actually boots, test your site in the browser. If you’re still not getting any meaningful info try just running the standard runserver

python manage.py runserver

Again, note any errors and if it loads fine, test your site in the browser. I suggest testing on localhost:8000 like you would in development. One of these should give you something to work with.

UPDATE

The error you’re getting says it can’t connect to “ind=127.0.0.1”. Then, looking at the command you’re running, gunicorn_django -bind=127.0.0.1:8001, it’s easy to see the problem. You can specify the IP and port to bind to with either -b or --bind. Since you only used one - it’s interpreting the IP as ind=127.0.0.1, which is obviously not correct. You need to use:

gunicorn_django --bind=127.0.0.1:8001

Or

gunicorn_django -b 127.0.0.1:8001
👤Chris Pratt

2đź‘Ť

You need to understand directives properly. “server_name” directive holds the IP address and “proxy_pass” will connect to port where your server is hosted. In your case:

server_name 127.0.0.1;
proxy_pass http://127.0.0.1:8001;

There is no reason for this not to work but still if it does not then try “python manage.py runserver” command to make sure that your site runs with no error because in case site is not able to present data to wsgi.py that likely to show same error.

0đź‘Ť

Increase the keepalive_timeout.

server {
        listen 5000 default deferred;
        client_max_body_size 4G;
        keepalive_timeout 5;
        server_name _;
        location / {
            proxy_read_timeout 800;
            proxy_pass  http://localhost:9000;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            break;
        }
}

0đź‘Ť

Try using a worker-class like gevent.
I had some trouble using gevent in python 3.7, better to use python 3.6.

Django, Python 3.6 example:

pip install gevent
gunicorn my_app.wsgi --workers 2 --worker-class=gevent --bind 0.0.0.0:80 --timeout=90 --graceful-timeout=10
👤Slipstream

Leave a comment