2

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.

Community
  • 1
  • 1
gatlanticus
  • 1,158
  • 2
  • 14
  • 28

1 Answers1

2

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

[Service]
EnvironmentFile=-/whatever/django_environment_settings
Michael Hampton
  • 9,737
  • 4
  • 55
  • 96
  • I clarified my answer. If you use the EnvironmentFile setting you restrict Django to working _only_ with systemd. – gatlanticus Jun 09 '15 at 06:25
  • No, you don't specify the environment variables in the unit file, you point to the external file that contains them. This will continue to work with your method. – Michael Hampton Jun 13 '15 at 17:56