1

I have a Django webapp running on an Ubuntu server using nginx and gunicorn. I'm trying to get my settings.py set up properly in regards to using environment variables to hide secret information such as the SECRET_KEY as well as API keys.

I've tried putting export SECRET_KEY='secret_key' in .bashrc as well as .profile, and using SECRET_KEY=os.environ['SECRET_KEY'] in my settings.py file, but this throws a 502 bad gateway error with nginx and its version at the bottom, upon restarting gunicorn. I'm not sure what else to try, as I'm pretty new to setting up servers.

I believe this is the init file for my gunicorn service:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=myuser
Group=www-data
WorkingDirectory=/home/myuser/myproject/mysite
ExecStart=/home/myuser/myproject/mysite/myprojectenv/bin/gunicorn --workers 3 --bind unix:/home/myuser/myproject/mysite/mysite.sock mysite.wsgi:application


[Install]
WantedBy=multi-user.target

I found this error in the nginx error log when trying to request the site, where it gives the 502 bad gateway:

*20 connect() to unix:/home/myuser/myproject/mysite/mysite.sock failed (2: No such file or directory)
6
  • Whose .bashrc are you using? What user are you running gunicorn as? How are you starting gunicorn? Jul 4, 2016 at 8:08
  • @DanielRoseman I'm using the .bashrc located in my user folder, this user I'm also using to run gunicorn (which is inside a virtualenv folder in my project). I'm not sure the exact method I'm using to start gunicorn, I'm simply using "service gunicorn restart" in order to apply changes to the server.
    – sidp
    Jul 4, 2016 at 8:11
  • Since you are using service to start gunicorn, that means you are running it under upstart. You should post the init script you are using. Jul 4, 2016 at 8:15
  • Where is this file typically located?
    – sidp
    Jul 4, 2016 at 8:19
  • Well it's in /etc/init/, but you must have put it there, it doesn't exist on its own. Jul 4, 2016 at 8:20

1 Answer 1

3

I solved this issue by putting my environment variables within the gunicorn.service file, located in /etc/systemd/system/, as export works only in the current shell.

Env variables were input in the file as the following format:

[Service]
Environment="SECRET_KEY=secret-key-string"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.