gatlanticus
gatlanticus

Reputation: 1226

Django and Gunicorn not working properly through systemd

While following this awesome tutorial for installing Django with Gunicorn, PostgreSQL and Nginx, I discovered that I couldn't user Supervisor as suggested, because it doesn't work with Python 3.

Since systemd is the default service manager on my Centos 7 server, I created a unit file to run gunicorn as per the tutorial. However, it failed with errors such as "no SECRET_KEY set" and "no PostgreSQL password supplied". Since everything was already working before systemd, these errors were weird.

Like many others, I was saving my secret Django settings as environment variables so as not to be stored publicly in my git repo. However, this page explained that environment variables in my ~/.bashrc would not be recognised, so I would have to make those variables accessible by systemd.

I have summarised my solution below for anyone who has the same difficulties with running Django through systemd.

UPDATE: The best solution allows systemd to work without compromising Django. While it's possible to state environment variables directly in a systemd unit file, this makes the variables inaccessible to Django when not running as a system daemon or debugging via the Python shell.

Upvotes: 2

Views: 1451

Answers (1)

Michael Hampton
Michael Hampton

Reputation: 9980

Just have the systemd unit read the environment from a file with EnvironmentFile=.

[Service]
EnvironmentFile=-/whatever/django_environment_settings

Upvotes: 2

Related Questions