Gunicorn Environment Variable Setting Gunicorn Environment Variable Setting django django

Gunicorn Environment Variable Setting


I got a similar problem when deploying gunicorn.service. And I passed environment variables to it by a file:

<on gunicorn.service>[Service]...EnvironmentFile=/pathto/somefilewith_secrets...

For example (cat /etc/systemd/system/gunicorn.service)

[Unit]  Description=gunicorn daemon  After=network.target    [Service]  User=ubuntuGroup=ubuntuWorkingDirectory=/home/ubuntu/10008/digichainOpenEnvironmentFile=/home/ubuntu/10008/digichainOpen/.envExecStart=/home/ubuntu/.local/share/virtualenvs/digichainOpen-Zk2Jnvjv/bin/gunicorn \          --worker-class=gevent --workers 4 \          --bind unix:/home/ubuntu/10008/digichainOpen/gunicorn.sock digichainOpen.wsgi:application            [Install]  WantedBy=multi-user.target  

and the .env file can be:

my_var=someValuesome_secret=secretvalueanother_secret=blah


You just have to export your environment variable.

export SERVER_ENV=TESTexport SERVER_ID=TESTgunicorn -b 127.0.0.1:8080 --error-logfile - --access-logfile - app.wsgi:application

And in your code you can get them like that

os.getenv('SERVER_ENV')


If you want to run Django using gunicorn config file:

Write a config.py file

command = 'venv/bin/gunicorn'pythonpath = 'venv'bind = '127.0.0.1:8000'workers = 2raw_env = ["VARIABLE_HERE=VARIABLE_VALUE_HERE"]wsgi_app = "project.wsgi"

Run it like this:From inside the project directory

gunicorn -c config.py