Hassan Baig Hassan Baig - 2 months ago 24
Python Question

Environment variables not being set after configuring Nginx and Gunicorn (Django app on Ubuntu machine)

I just set up Gunicorn with Nginx (reverse proxy) for a Django web app. The combo seems to be firing up correctly as per

gunicorn.log
. Note that I'm not using supervisor.

But curiously, my environment variables (set in
.profile
) aren't being picked up at all!
printenv
shows they exist. Some things I've tried are putting the environment variables in
/etc/default/nginx
and restarting nginx, in
etc/environment
, in
.profile
, in
nginx.conf
, in
gunicorn.conf
, etc. It just doesn't work!

By the way, it worked perfectly before installing and configuring nginx, i.e. when I was simply running:
gunicorn --bind 0.0.0.0:8080 --env DJANGO_SETTINGS_MODULE=myproject.settings myproject.wsgi:application
.

Now it seems that nginx:


removes all environment variables inherited from its parent process
except the TZ variable


Source: http://nginx.org/en/docs/ngx_core_module.html#env Could this be the reason why nothing I'm trying has come close to working? But if so, these variables added to nginx.conf ought to have been picked up I suppose. Nevertheless, using
echo $envvar
yields the correct value on the command line, which tells me that perhaps the variables are set, but being bypassed or overlooked. Note that the
USER
env variable shows up as None too, whereas print
TERM
prints linux.




wsgi.py:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())


gunicorn.conf:

description "Gunicorn application server handling myproject"

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid myuser
setgid www-data
chdir /home/myuser/directory/myproject/

exec /home/myuser/.virtualenvs/myvirtualenv/bin/gunicorn --chdir=/home/myuser/directory/ --workers 3 --bind unix:/home/myuser/directory/myproject/myproject.sock --env DJANGO_SETTINGS_MODULE=myproject.settings myproject.wsgi:application


/etc/nginx/sites-available/myproject:

server {
listen 80;
server_name myapp.cloudapp.net;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/myuser/directory/myproject;
}

location / {
include proxy_params;
proxy_pass http://unix:/home/myuser/directory/myproject/myproject.sock;
}
}


Note: ask me for more information in case you need it.

Answer

So an air-tight (hopefully) way of setting environment variables that gunicorn would have no trouble seeing is editing gunicorn.conf as follows:

exec /home/myuser/.virtualenvs/myvirtualenv/bin/gunicorn --chdir=/home/myuser/directory/ --workers 3 --bind unix:/home/myuser/directory/myproject/myproject.sock -e var1=value1 -e var2=value2 myproject.wsgi:application

This has served me well so far. If I run into any issues, I'll update this answer.

Comments