How to Set Docker Environment Variables [With Examples]

October 10th, 2023
How to Set Docker Environment Variables [With Examples]

Docker is a powerful tool that allows users to maintain a consistent development environment across various platforms. Docker environment variables are important configurations that impact all applications within a Docker container.

This tutorial explains everything you need to know about Docker environment variables. We list various ways to set environment variables in Docker, including how to set or override them using Docker CLI commands and Docker Compose, and some best practices to follow.

What are Docker environment variables?

Docker environment variables are constant values that apply to all the applications running within a Docker container. These variables are used in many scenarios, such as to define the behavior of an application or script, configure parameters for docker images, and store important credentials like database credentials and API secrets.

What's more, environment variables in Docker are critical to enhancing the container's portability and flexibility. Environment variables let you adjust settings based on where you deploy the container without recreating the whole image and allow you to inject configurations at run time, enabling the container to work in various places and improve portability.

Ready to supercharge your Docker infrastructure? Scale effortlessly and enjoy flexible storage with Cherry Servers bare metal or virtual servers. Eliminate infrastructure headaches with free 24/7 technical support, pay-as-you-go pricing, and global availability.

1. How to set environment variables in Dockerfile

A Dockerfile specifies everything it needs to build a Docker image. You can define two types of variables in the Dockerfile:

  • Type 1: ENV - environment variables
  • Type 2: ARG - build time variables

The ENV contains environment variables that will be applied for any container built from it. You can specify the variables according to the following format.

ENV: env_variable_name=value

The following shows an example of a Dockerfile with environmental variables.

Dockerfile with environmental variables

When you run a container from the image created with that Dockerfile, the applications or tasks within can use the Dockerfile environment variables.

2. How to view environment variables in Docker

Docker provides a few options for inspecting and viewing the environmental variables currently set in the containers for debugging purposes.

Option 1: Use docker inspect command

You can use the docker inspect command to see what environmental variables have been set in your container or the docker image and check the Env part of the JSON that generates. You need to specify the container or image ID.

docker inspect <containerId>/<Image_id>

To view only the environmental variables, use the following format of the inspect command.

docker inspect --format '{{.Confing.Env}}' <containerId>/<Image_id>

dockerfile ps

dockerfile images

Option 2: Use docker exec command

Another way to see the configured environment variables is using Docker exec command. Use the docker exec command following the format.

docker exec <containerID> env

dockerfile exec

3. How to set and override Docker environment variables using docker run command

Docker environment variables are defined in the Docker file or a separate environment file. When starting a container, you can set environmental variables using the command line using the docker run command. You can also override the existing environment variables, specifying new values.

When using the docker run command, you can specify environmental variables in several ways.

Option 1: Use the -e option

You can use the -e flag to set or override an environment variable when running a container. You can specify multiple variables by using multiple -e flags.

docker run -e env_var=value <imageName>

Following is an example:

use -e

You can check if it is actually set by checking the images’ container id, as stated in the first section.

checking the images’ container id

Option 2: Use the --env-file option

Another way to set or override environmental variables is using the --env-file option.

docker run --env-file <env_file_name> <imageName>

For example, we defined the following environmental variables in a dev.env file.

API_KEY=WENMCOMnhfwDWER
MONGODB_URL=https://monogodbURL:uname:pw

set environment variables

set environment variables - env

In addition, you can also combine both -e and --env-file options to set and override environmental variables. If you set the same environment variable using both options, both the values will be set as Docker environment variables, and what you have defined using the -e option will take precedence.

4. How to set and override Docker environment variables using Docker Compose

Setting Docker environment variables at run time using the CLI is not a good practice for multi-container applications. Instead, we can use a special configuration file docker-compose.yaml to define all environmental variables. This file contains all the configurations applicable to the container, and using one command, you can apply them when running the container.

set docker container

set docker container - env

Option 1: Use the environment attribute in the docker-compose.yaml file.

A typical docker-compose.yaml file will look like this. You can define the environmental variables in the environment section.

services:
  web:
    build: 
    environment:
      - key1="value1"
      - key1="value1"

Let’s first clone the repository at https://github.com/wiztechth/compose-redis/tree/master, which will create a web application.

git clone https://github.com/wiztechth/compose-redis/tree/master

Next, define the following environmental variables in the docker-compose.yaml file.

 environment:
      - DEBUG=1
      - ENV="staging"

docker-compose.yaml file

Execute the following command by going into the application from the command line. It works exactly like the command docker run -e key=value

docker compose up

Next, using the following command, open up a new terminal window and check if the environmental variables you have defined have been applied using the docker compose run command.

docker compose run web env

Check how all the variables you have set have been applied. All other environmental variables come from the Dockerfile.

docker compose run web env

Option 2: Specify a separate environment variable file in docker-compose.yaml file

Alternatively, you can use a separate file to define your environmental variables and define that file in the env_file section of the docker-compose.yaml file. For our example, let’s create a .env file and specify the following environmental variables with values.

REDIS_PASSWORD=test
LOG_LEVEL=INFO

Then, include the path in the docker-compose.yaml file as follows.

services:
  web:
    build: 
    ports:
      - "8000:5000"
   env_file:
      - .env
  redis:
    image: "redis:alpine"

docker-compose.yaml file

In addition, you can use the following command to see the environmental variables configured to the application.

docker compose config

see env varibles configured

Also, you can combine multiple environmental variable files. To check this, rename the .env file as stg.env and specify both the file paths as follows.

services:
  web:
    build: 
    ports:
      - "8000:5000"
    env_file:
      - dev.env
      - stg.env
  redis:
    image: "redis: alpine"

set multiple env files

Specifying environmental variables in a separate file like this makes the containers flexible. For example, you can save the file in any location and give it a specific name, such as dev.env, prod.env, etc., according to the application's environment. Therefore, you can have environment-specific configurations separately to organize your applications.

Option 3: Set Docker environment variables with docker compose at the run time

In addition, docker compose also allows setting environment variables in the command line using the --env-file option.

docker compose --env-file <environmental_variables_file> up

To see how it works, add the following new sample environmental variable to the .env file you have created.

MONGODB_PASSWORD=test

Then run the application and check the configured environmental variables.

docker compose --env-file

docker compose --env-file - env

Option 4: Use docker compose run to set one-off environment variables

Another way to set environmental variables is when you use the ‘docker compose run’ command. The docker compose run executes run one-off commands. This is exactly similar to the docker run command. Similarly, you need to use the e or --env-file option with it.

The environment variables you set in this manner apply only to that particular container run. They will not be preserved for future containers you start from the same image unless you set them again.

For example, the following command will change the value of the variable DEBUG in our web application.

docker compose run -e DEBUG=0 web

docker compose run

docker compose run - env

Explore how web hosting service provider Debesis improved its service quality, performance, and reliability by migrating to Cherry Servers' bare-metal servers.

"Cherry Servers engineers always help when we need them, while their customer service quality is a blast!"

Best practices when setting Docker environment variables

When setting Docker environment variables, it is important to follow some best practices. Following are some important ones you could consider.

  1. Use a separate .env file to set Docker environment variables: it will help you to organize your variables across different environments. However, if you are deploying the docker repositories, ensure that you add it to the .gitignore file to prevent from committing them;
  2. Encrypt and store sensitive data: you should not define sensitive data like passwords and API keys directly in plain text. Use some form of encryption to store them and decrypt them within the application when using them;
  3. Avoid changing environment variables within a running container: to ensure consistency between different environments, never change them at run time. Instead, change after the container is stopped and start a new instance;
  4. Use a standard naming convention: to ensure consistency, use a standard naming convention;
  5. Maintain the environmental variables regularly: review the defined environment variables regularly to ensure there are no outdated values.

Wrapping up

In this guide, we discussed the significance of Docker environment variables in ensuring consistent behavior for applications across various platforms. We've highlighted the role of the Dockerfile environment variables and explored how Docker offers flexibility in adjusting them through CLI commands and Docker Compose. Moreover, by adopting the best practices we highlighted, you can securely manage sensitive data, achieve consistent configurations, and enhance container deployment efficiency.

Run your Docker containers at scale with Cherry Servers open cloud infrastructure. Choose a dedicated bare metal or virtual server with flexible storage, pricing, global availability, and free 24/7 technical support to focus on your container development workflow.

Mantas is a hands-on growth marketer with expertise in Linux, Ansible, Python, Git, Docker, dbt, PostgreSQL, Power BI, analytics engineering, and technical writing. With more than seven years of experience in a fast-paced Cloud Computing market, Mantas is responsible for creating and implementing data-driven growth marketing strategies concerning PPC, SEO, email, and affiliate marketing initiatives in the company. In addition to business expertise, Mantas also has hands-on experience working with cloud-native and analytics engineering technologies. He is also an expert in authoring topics like Ubuntu, Ansible, Docker, GPU computing, and other DevOps-related technologies. Mantas received his B.Sc. in Psychology from Vilnius University and resides in Siauliai, Lithuania.

Start Building Now

Deploy your new Cloud VPS server in 5 minutes starting from $5.83 / month.

We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: b0376f5bd.760