Docker environment variables and NGINX
This post will demonstrate how to set environment variables inside docker and how to use them inside your NGINX configuration.
We will use the official nginx docker image as the base image here, so all commands will be based on alpine linux. Keep in mind that you have to adjust the commands according to your OS.
The use case
We have a docker container that we deploy to multiple environments and want to enable basic auth on every environment except the production one.
Basic setup
We start with a basic docker setup using the nginx:alpine image.
We can now build and run our basic container with the following commands:
$ docker build -t basic-docker-nginx .
$ docker run -d -p 8080:80 basic-docker-nginx
Visiting http://localhost:8080/ in your browser to see the good old “Hello World” caption.
Reaching the goal
Now that we have something to build upon we can implement our basic auth protection for every environment except production.
First, we need to tell the Dockerfile to set an environment variable called ENV.
We can achieve this with the ENV directives.
...
ENV ENV
...
The next step ist to use the new environment variable inside NGINX to enable basic auth. Unfortunately, NGINX is not able to use custom environment variables out of the box, so we need to install an additional module: nginx-mod-http-perl
Note: At the end of this post you can find the whole code for our little example container.
Now we are able to use perl inside our main nginx.conf file set and NGINX environment variable.
...
load_module "modules/ngx_http_perl_module.so";
env ENV;http {
...
perl_set $env 'sub { return $ENV{"ENV"}; }';
...
}
...
The last step is to access the new NGINX environment variable inside the default.conf file.
...
if ($env != 'PROD') {
set $auth_basic "Restricted Content";
}
if ($env = 'PROD') {
set $auth_basic off;
}
auth_basic $auth_basic;
auth_basic_user_file /etc/nginx/.htpasswd;
...
Try it
To start our new container we can simple use the previous command:
$ docker build -t basic-docker-nginx .
$ docker run -d -p 8080:80 basic-docker-nginx
When starting our container in production we only need to set the environment variable value in the second command:
$ docker run -d -p 8080:80 -e "ENV=PROD" basic-docker-nginx
Full code snippet
The .htpasswd password is bar