Environment Variables in NGINX Config with Docker

nginx Mar 11, 2020

In this article we will Pass Docker Environments to Nginx Default Config. Lets get it started

Firstly create startup.sh shell script file like below

#!/bin/bash
chmod 777 /etc/nginx/conf.d/default.conf
sed -i "s/__LISTEN__/$LISTEN/g" /etc/nginx/conf.d/default.conf;
sed -i "s/__SERVER__/$SERVER/g" /etc/nginx/conf.d/default.conf;

sed -i "s/__PROTOCOL__/$PROTOCOL/g" /etc/nginx/conf.d/default.conf;
sed -i "s/__HOST__/$HOST/g" /etc/nginx/conf.d/default.conf;
sed -i "s/__PORT__/$PORT/g" /etc/nginx/conf.d/default.conf;

Then create default.conf nginx config file

server {
    listen __LISTEN__;
    server_name __SERVER__;

    location / {
        proxy_pass __PROTOCOL__://__HOST__:__PORT__;
    }
}

When Container up before nginx started we will change ENV_NAME from Docker ENV.
so Finally create Dockerfile for this

FROM ubuntu:14.04

MAINTAINER Muhammet GÜMÜŞ (muhgumus@gmail.com)

# install nginx
RUN apt-get update -y
RUN apt-get install -y python-software-properties
RUN apt-get install -y software-properties-common
RUN add-apt-repository -y ppa:nginx/stable
RUN apt-get update -y
RUN apt-get install -y nginx

# deamon mode off
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf
RUN chown -R www-data:www-data /var/lib/nginx

# expose ports
EXPOSE 8001

ADD config/default.conf /etc/nginx/conf.d/default.conf
ADD startup.sh /etc/nginx/startup.sh

WORKDIR /etc/nginx

ENV LISTEN "8001"
ENV SERVER "localhost"
ENV PROTOCOL "http"
ENV HOST "echo"
ENV PORT "80"

CMD chmod +x ./startup.sh; sync; ./startup.sh; sync; nginx

Now build docker image docker build -t myngin .
and run it docker run -e "LISTEN=3001" -e "HOST=mybackendservice" mynginx like this

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.