Tirtha Guha
Posted on September 5, 2020
In this post, we'll learn how to set environment variables in docker containers. Often things like password, environment configurations, API credentials etc are not checked in the repositories as a security measure. These are set in environment variables, from where the application reads it during the runtime.
Create a sample application
For this, we'll create a simple express application which will read the environment variable and show it on the browser
- run npm init to create a package json
$ mkdir test-app
$ cd test-app
$ npm init --y
$ npm install express --save
$ touch app.js
- Open
app.js
and type in the following
// app.js
var express = require("express");
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get("/", function (req, res, next) {
res.send({ title: "Express", envVal: process.env.TESTVAL });
});
app.listen(3000, () => console.log("Running on http://localhost:3000"));
- add the start script in package.json
{
"name": "express-with-env",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "~4.16.1"
}
}
- Run the application
I'm using ubuntu v18 for development. If you're on windows, you may need to set the env variable in a slightly different way.
$ TESTVAL=QWERTY npm start
Now if you open http://localhost:3000 in the browser, you would see
{
"title": "Express",
"envVal": "QWERTY"
}
Create the docker image
Let's create a Dockerfile, parallel to your packageJSON
$ touch Dockerfile
$ touch .dockerignore
Lets now open Dockerfile and add these entries into it.
FROM node:12-slim
WORKDIR /app
COPY ./package*.json ./
RUN npm install
COPY ./ ./
EXPOSE 3000
# Run the code
CMD [ "npm", "start" ]
Build the docker image from the Dockerfile
$ sudo docker build -t test-image .
Finally run the image with an entrypoint
$ sudo docker run -e "TESTVAL=Docker with env variable" -p 3000:3000 -d test-image
if you now open http://localhost:3000 in a browser, you'll get
{
"title": "Express",
"envVal": "Docker with env variable"
}
Let spin up another container from the same image
$ sudo docker run -e "TESTVAL=Another Docker Container from the same image" -p 4000:3000 -d test-image
if you now open http://localhost:4000 in a browser, you'll get
{
"title": "Express",
"envVal": "Another Docker Container from the same image"
}
PS:
Often enterprises have multiple prod and non-prod environments to support. Each environment often have different configurations, but your code must follow the strategy build once deploy anywhere. With this tutorial, you'll be able to do that effectively.
Posted on September 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.