Search code examples
djangoubuntunginxgunicornproduction-environment

How to access and set Environment Variables any production (Nginx and Gunicorn)


I am trying to set Environment Variables for a Nginx And Gunicorn Served Django Project on Ubuntu. The variables are set for the Ubuntu user and i am able to see the value using printenv VAR_EMAIL.

But when i use them django settings it is not working , using them as os.environ['VAR_EMAIL'],This doesn't get the value of the variable in production and server doesn't work.

However this works on Development side.

UPDATE 1st May 2020: I used systemd and passed the variable like this in gunicorn.service file.This won't work still get key error,)Will post the exact error) as it is production on Ubuntu but i am developing on Windows and it works fine with Environment Variables in Development. is os.environ['var_name'] correct way to access that ? I also tried os.environ.get('var_name') as i saw in some video that environ have .get() to access the value. I will try again maybe i made some mistake.Feel free to ask for any info required. Service File

ANSWERED - It was error on my end.


Solution

  • What are you using to supervise and run the gunicorn process in Ubuntu? If you're not using any, I recommend you to use systemd, there's a small guide on how to setup in the gunicorn docs: https://docs.gunicorn.org/en/stable/deploy.html#systemd

    After that, you can set the environment variables in the systemd config file doing like the following, under the [Service] section of the systemd config file:

    [Service]
    Environment="VAR_EMAIL=var-email"
    Environment="ANOTHER_VAR=another-var"
    

    You can also use the EnvironmentFile directive if you prefer to have these variables in a separate file: https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=