Set Environment Variables Inside a Dockerfile

In our previous post, we showed how to build a Docker image using a Docker file, and today we will show how to declare an environment variable inside a Docker file.

To visit the previous about building a Docker image with a Dockerfile, click here.

Using environment variables inside a Docker file and, in general, help us write a cleaner code and not hard code values. Variables are declared once and referenced in the application or the Dockerfile.

ENV

With Docker, we set environment variables using the env statement inside the Dockerfile. In the example below, I’m setting a variable that holds a directory name that I will use to create a directory using the run statement.

FROM ubuntu
ENV builddir=build
RUN mkdir ${builddir}

I can also reference the variable using $builddir without using {}.

When I deploy a container from the image, I will see a directory called build.


Posted

in

,

by