Ruan Bekker's Blog

From a Curious mind to Posts on Github

Docker Environment Substitution With Dockerfile

The 12 Factor way, is a general guideline that provides best practices when building applications. One of them is using environment variables to store application configuration.

What will we be doing:

In this post we will build a simple docker application that returns the environment variable’s value to standard out. We are using environment substitution, so if the environment variable is not provided, we will set a default value of NOT_DEFINED.

We will have the environment variable OWNER and when no value is set for that Environment Variable, the NOT_DEFINED value will be returned.

The Dockerfile

Our Dockerfile:

1
2
3
FROM alpine:edge
ENV OWNER=${OWNER:-NOT_DEFINED}
CMD ["sh", "-c", "echo env var: ${OWNER}"]

Building the image:

1
$ docker build -t test:envs .

Putting it to action:

Now we will run a container and pass the OWNER environment variable as an option:

1
2
$ docker run -it -e OWNER=ruan test:envs .
env var: ruan

When we run a container without specifying the environment variable:

1
2
$ docker run -it ruan:test
env var: NOT_DEFINED

Resources:

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!