Pass Environment Variables to Docker Containers

In this blog post, we will go over the Docker environment variables and the different ways you can set them.

Docker is a platform that was designed to automate the deployment of applications inside software containers. These containers have their own filesystems and system utilities, but share host resources such as kernel namespaces, networking interfaces, security policies and storage backends. The goal of Docker is to allow developers who are working on large projects that use multiple languages or frameworks to deploy products quickly by providing a simpler way for these developers to package up their code into small containers that can be deployed anywhere in seconds without worrying about conflicts with other packages from other people. One of the best features of Docker is its ability to create isolated environments where your application can run without affecting other applications on your machine.

Docker is pretty smart at reading the environment variables and exposing them to containers and they can be used by running scripts or inside Dockerfiles. Environment variables are a key tool to allow you to configure the behaviour of docker containers and we will look into them now.

Environment Variables Overview

There are four types of environment variables:

1. Use the -e Flag

The ones added with the -e (or –env ) flag and can be set during runtime and will be accessible to all processes running inside the container. ¬†These variable values are also listed in docker inspect <container_id> .

2. Use a Dockerfile

The ones added with the ENV command in a Dockerfile. These are set on container startup and can be used to initialize process-specific configuration files.

3. Command Specific

The ones added with the -e (or –env ) flag but specifically for a given command during runtime. For example, you could run the following command: docker run -e “myvariable=somevalue” myimage somecommand . These variable values are not visible in docker inspect <container_id> ¬†and they can only be used inside the container.

4. File

The ones added with the –env-file flag to specify a file with additional environment variables. These will be set on startup of any containers created from that image and can be used to initialize process-specific configuration files.

Deploy Container with Variables

In the below example, I am creating a new container and passing two variables using the –env option.

docker run --env myvar1=test --env myvar2=code ubuntu

We can also pass exported variables to the container by first exporting them to the host using the export command.

export myvar=test
export myvar1=vcode

Then I can run the following command and pass them to the container.

 docker run --env myvar1 --env myvar2 ubuntu 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.