Correct gunicorn.conf to get environmental variables for Django use

放肆的年华 提交于 2019-12-03 10:16:49

问题


I am deploying a Django app on my VPS using Nginx as the web server and Gunicorn installed in virtualenv. (I am using virtualenv with virtualenvwrapper.)

When I run Gunicorn like this, environment variables (such as database password, name) can be found:

workon virtual_env_name
# from my_project's root path
gunicorn my_project.wsgi --bind localhost:9000 --daemon
# this works

I exported the environment variables this way:

# /home/user_name/Envs/virtual_env_name/bin/postactivate
export DATABASE_PASSWORD="secret_password"

However the way below does not (whether or not virtual_env_name is activated):

sudo service gunicorn start
# env variables can't be found - KeyError thrown

This is how my gunicorn.conf script looks like:

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectadly trigger a respawn
respawn

setuid user_name
setgid www-data
chdir /home/user_name/my_project

exec /home/user_name/Envs/virtual_env_name/bin/gunicorn \
    --name=my_project \
    --pythonpath=/home/user_name/my_project \
    --bind=127.0.0.1:9000 \
    my_project.wsgi:application

I can confirm this gunicorn.conf works if I hard code all the password, keys into my Django's settings.py instead of using os.environ[..].

What do I need to do to make my environment variables found when I start Gunicorn with sudo service start? What's the difference between the first and second way? Thanks.


回答1:


You need to define those variables inside gunicorn.conf.

env DATABASE_PASSWORD="secret_password"



回答2:


You don't run the code in virtualenv.

Instead of exec use

pre-start script
    workon virtual_env_name
end script

script
    gunicorn \
        --name=my_project \
        --pythonpath=/home/user_name/my_project \
        --bind=127.0.0.1:9000 \
        my_project.wsgi:application
end script

workon update Your $PATH env variable.



来源:https://stackoverflow.com/questions/33652720/correct-gunicorn-conf-to-get-environmental-variables-for-django-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!