Nginx – Serving django with nginx and uWSGI

djangonginxpythonuwsgi

I followed this post to serve my django project. The project runs well with manage.py runserver and I want to set it up for production. Here are my setting files:

nginx.conf:

upstream django {
    server /tmp/vc.sock;
    #server 10.9.1.137:8002;
}

server {
    listen      8001;
    server_name 10.9.1.137;
    charset     utf-8;
    client_max_body_size 25M;

    location /media  {
        alias /home/deploy/vc/media;
    }
    location /static {
        alias /home/deploy/vc/static;
    }


    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params;
    }
}

uwsgi.ini:

[uwsgi]

chdir           = /home/deploy/vc
wsgi-file      = vc/wsgi.py

master          = true
processes       = 2
#socket          = :8002
socket          = /tmp/vc.sock
chmod-socket    = 666
vacuum          = true

If I use TCP port socket (server 10.9.1.137:8002 and socket = :8002), it's going to be fine. However if I comment them out and use Unix sockets(server /tmp/vc.sock and socket = /tmp/vc.sock), the server will return 502 error. How should I fix it?

Here's the nginx error log when I run /etc/init.d/nginx restart

nginx: [emerg] invalid host in upstream "/tmp/vc.sock" in /etc/nginx/conf.d/vc.conf:2
nginx: configuration file /etc/nginx/nginx.conf test failed

And this is the warning when I run uwsgi --ini vc/uwsgi.ini:

*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** 

Can't I run uWSGI as root?

Best Answer

An upstream server which uses a Unix domain socket must be declared as such:

upstream django {
    server unix:/tmp/vc.sock;

And yes, I suppose you could run uWSGI as root, but you absolutely positively should not. This is security 101. The uWSGI project even go so far as to call it common sense:

Common sense: do not run uWSGI instances as root. You can start your uWSGIs as root, but be sure to drop privileges with the uid and gid options.


BTW, your server block could use a root directive. That would let you get rid of those pointless redundant locations for your static assets.

    root /home/deploy/vc;