如何使用systemd设置gunicorn读取自定义设置

时间:2016-10-11 14:15:14

标签: django gunicorn

我迁移了我必须使用的服务器到Ubuntu 16.04而systemd取代了upstart。我有三个开发环境:生产,分期和开发。只有后一个使用本地数据库,另外两个使用远程数据库。 因此,为了处理部署和服务,我设法创建了以下systemd服务文件:

[Unit]
Description=Gunicorn service for Project
After=network.target

[Service]
User=projuser
WorkingDirectory=/home/projuser/sites/Project/source
ExecStartPre=/usr/bin/env DJANGO_SETTINGS_MODULE=v3.settings_staging
ExecStart=/home/projuser/sites/Project/env/bin/gunicorn --bind 127.0.0.1:8090 --workers 6 --access-logfile ../access.log --error-logfile ../error.log v3.wsgi:application

[Install]
WantedBy=multi-user.target

服务启动,但似乎忽略了这一行:ExecStartPre=/usr/bin/env DJANGO_SETTINGS_MODULE=v3.settings_staging。我可以在日志中看到以下内容:

django.db.utils.OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

主要是因为它使用了我用于开发的默认settings.py文件。

如何确保加载staging settings.py文件?

1 个答案:

答案 0 :(得分:2)

好吧,作为gunicorn的参数传递也有效:

--env DJANGO_SETTINGS_MODULE=myproject.settings

https://gunicorn-docs.readthedocs.io/en/latest/run.html#gunicorn-django

通过在/etc/systemd/system中添加以下文件,可以实现我想要的目标:

[Unit]
Description=Gunicorn service for a Django Project
After=network.target

[Service]
User=a_user
WorkingDirectory=/home/a_user/project/source
Environment="DJANGO_SETTINGS_MODULE=app.settings_staging"
ExecStart=/home/a_user/envs/project_env/bin/gunicorn --bind 127.0.0.1:8090 --workers 6 --access-logfile ../access.log --error-logfile ../error.log v3.wsgi:application

[Install]
WantedBy=multi-user.target

请注意以下一行:Environment="DJANGO_SETTINGS_MODULE=app.settings_staging"

https://www.linux.com/learn/understanding-and-using-systemd