How can I use environment variables in Nginx.conf

Hugo Rodger-Brown asked:

[Cross-posted and edited down from as it was considered too sysadmin-like for StackOverflow.]

I have a docker container running Nginx, that links to another docker container. The host name and IP address of the second container is loaded into the Nginx container as environment variables on startup, but is not know before then (it’s dynamic). I want my nginx.conf to use these values – e.g.

upstream gunicorn {

How can I get environment variables into the Nginx configuration on startup?


This is the entire file, after the suggested answer below:

# Nginx host configuration for django_app

# Django app is served by Gunicorn, running under port 5000 (via Foreman)
upstream gunicorn {
    server $ENV{"APP_WEB_1_PORT_5000_TCP_ADDR"}:5000;

server {
    listen 80;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location /static/ {
        alias /app/static/;
    location /media/ {
        alias /app/media/;
    location / {
        proxy_pass http://gunicorn;

Reloading nginx then errors:

$ nginx -s reload
nginx: [emerg] unknown directive "env" in /etc/nginx/sites-enabled/default:1

I answered:

You need to do two things:

  1. First specify the environment variables that you want nginx to read with the env directive. This must be done in the very top scope, before even http or server.

    env APP_HOST_NAME;
    env APP_HOST_PORT;
  2. Then in your configuration, you use these environment variables.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.