Hassan Baig Hassan Baig - 27 days ago 10x
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

. Note that I'm not using supervisor.

But curiously, my environment variables (set in
) aren't being picked up at all!
shows they exist. Some things I've tried are putting the environment variables in
and restarting nginx, in
, in
, in
, in
, 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 --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
env variable shows up as None too, whereas print
prints linux.


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())


description "Gunicorn application server handling myproject"

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

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


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.


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.