Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How setup gunicorn to read custom settings with systemd

I migrated a server I had to Ubuntu 16.04 and systemd replaced upstart. I have three developing environments: Production, Staging and Development. Only the latter one uses a local database, the other two use a remote one. So, in order to handle the deployment and the service I managed to create the following systemd service file:

[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

The service starts, but it seems to ignore this line: ExecStartPre=/usr/bin/env DJANGO_SETTINGS_MODULE=v3.settings_staging. I can see in the logs the following:

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?

Mostly because it is using my default settings.py file, which I use for development.

How can I make sure it loads the staging settings.py file?

like image 865
Ev. Avatar asked Oct 11 '16 14:10

Ev.


1 Answers

Well, passing as an argument to gunicorn also works:

--env DJANGO_SETTINGS_MODULE=myproject.settings

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

What I wanted could be achieved by having the following file in /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

Note the following line: Environment="DJANGO_SETTINGS_MODULE=app.settings_staging".

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

like image 76
Ev. Avatar answered Sep 19 '22 18:09

Ev.