How Can You Use Environment Variables in CMD with Docker?

Using environment variables in CMD with Docker is a good way to set up your applications while they run. We do not need to hardcode values. Environment variables help us manage settings, secrets, and runtime information easily. This makes our Docker containers more flexible and safe. By using these variables, we can build applications that are portable and can change based on where they run.

In this article, we will look at different ways to use environment variables in Docker. We will learn how to set them in a Dockerfile. We will also see how to pass them when we run docker run and how to use them in Docker Compose. We will explain how to access these variables inside Docker containers. We will also use them for managing secrets. Here is what we will talk about:

  • How to Use Environment Variables in CMD with Docker
  • How Can You Set Environment Variables in Dockerfile
  • How Can You Pass Environment Variables at Docker Run
  • How Can You Use Environment Variables in CMD for Docker Compose
  • How Can You Access Environment Variables Inside Docker Containers
  • How Can You Use Environment Variables for Secrets in Docker
  • Frequently Asked Questions

For more information on Docker, you can check articles like What is Docker and Why Should You Use It? and How Does Docker Differ from Virtual Machines?.

How Can We Set Environment Variables in Dockerfile

We can set environment variables in a Dockerfile using the ENV instruction. This helps us define environment variables that will be available in the container when it runs. The syntax looks like this:

ENV <key>=<value> ...

Example of Setting Environment Variables

Here is an example Dockerfile where we set some environment variables:

FROM ubuntu:latest

# Set environment variables
ENV APP_HOME=/usr/src/app
ENV APP_ENV=production
ENV APP_VERSION=1.0.0

# Create the application directory
RUN mkdir -p $APP_HOME

# Set the working directory
WORKDIR $APP_HOME

# Copy application files
COPY . .

# Run the application
CMD ["python", "app.py"]

Accessing Environment Variables

We can access these environment variables in our application code. This depends on the programming language we use. For example, in Python, we can get environment variables with the os module:

import os

app_env = os.getenv('APP_ENV')
print(f"Running in {app_env} environment")

Best Practices

  • Use all uppercase letters for environment variable names. This helps to tell them apart.
  • Write down our environment variables in the Dockerfile. This makes it clear.
  • Do not hardcode sensitive information in the Dockerfile. We should think about using Docker secrets or passing variables when we run it.

For more details about using Dockerfiles, check out what is the Dockerfile and how do you create one.

How Can We Pass Environment Variables at Docker Run

We can pass environment variables to a Docker container when we run it. We use the -e flag with the docker run command. This helps us set different settings and secrets for our application without putting them directly in our images.

Syntax

docker run -e VARIABLE_NAME=value image_name

Example

If we want to pass an environment variable called DATABASE_URL to a container that runs a Node.js application, we would do it like this:

docker run -e DATABASE_URL=mongodb://localhost:27017/mydatabase my-node-app

Multiple Environment Variables

We can also pass more than one environment variable by adding more -e flags:

docker run -e VARIABLE1=value1 -e VARIABLE2=value2 image_name

Using Environment Variables from a File

We can use the --env-file option to load environment variables from a file. First, we create a .env file with this content:

DATABASE_URL=mongodb://localhost:27017/mydatabase
API_KEY=myapikey

After that, we run:

docker run --env-file .env my-node-app

Accessing Environment Variables in Our Application

Inside our application, we can access the environment variables using the usual method for our programming language. For example, in Node.js, we do:

const dbUrl = process.env.DATABASE_URL;

This way of passing environment variables at runtime helps us keep our setup safe and flexible. It lets us manage our settings outside of the Docker images. For more info, we can check how to use environment variables in Docker.

How Can We Use Environment Variables in CMD for Docker Compose

In Docker Compose, we can use environment variables to set up our services in a flexible way. We can define these environment variables in different ways. These ways include the docker-compose.yml file, an .env file, or right in the shell. Let’s look at how to use them.

Defining Environment Variables in docker-compose.yml

We can add environment variables directly in our docker-compose.yml file. We do this under the environment section for a service.

version: '3.8'
services:
  web:
    image: nginx
    environment:
      - NODE_ENV=production
      - API_URL=http://api.example.com

Using an .env File

We can create a .env file in the same folder as our docker-compose.yml. The variables we write in this file will load automatically.

Example of an .env file:

NODE_ENV=production
API_URL=http://api.example.com

Referencing in docker-compose.yml:

version: '3.8'
services:
  web:
    image: nginx
    environment:
      - NODE_ENV=${NODE_ENV}
      - API_URL=${API_URL}

Passing Environment Variables at Runtime

We can also pass environment variables when we run our commands. We use the -e flag with the docker-compose command.

docker-compose up -e NODE_ENV=production -e API_URL=http://api.example.com

Accessing Environment Variables in Containers

Inside our application that runs in the Docker container, we can access the environment variables. We use the normal way for the programming language we are using. For example, in Node.js, we can access them like this:

console.log(process.env.NODE_ENV);
console.log(process.env.API_URL);

Using Environment Variables for Secrets

For sensitive information like passwords or API keys, it is better to use Docker secrets. We can define secrets in our docker-compose.yml file and then use them in our service.

Example:

version: '3.8'
services:
  web:
    image: nginx
    secrets:
      - db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt

This way, we can keep sensitive information safe and not show it in our code.

By using environment variables in CMD for Docker Compose, we can make our applications flexible. They can change easily for different environments. For more detailed information about environment variables and how to use them in Docker, we can check this article.

How Can We Access Environment Variables Inside Docker Containers

To get environment variables inside Docker containers, we can use the printenv command or get them in our application code. Here is how we can do it:

  1. Using Command Line:
    We can run a command in a running container to show all environment variables:

    docker exec <container_name_or_id> printenv
  2. Accessing in Application Code:
    In different programming languages, we can access environment variables using their own methods:

    • Python:

      import os
      db_host = os.getenv('DB_HOST')
    • Node.js:

      const dbHost = process.env.DB_HOST;
    • Bash:

      echo $DB_HOST
  3. Setting Environment Variables on Container Startup:
    If we want to pass environment variables when starting the container, we can use the -e flag:

    docker run -e DB_HOST=mydatabase.com myimage
  4. Dockerfile Example:
    We can also set environment variables in our Dockerfile using the ENV instruction:

    FROM ubuntu:latest
    ENV DB_HOST=mydatabase.com
  5. Docker Compose:
    In docker-compose.yml, we can define environment variables under the service:

    version: '3'
    services:
      app:
        image: myapp
        environment:
          - DB_HOST=mydatabase.com

By using these ways, we can easily access and manage environment variables inside our Docker containers. For more details on how to use environment variables, we can check this guide on using environment variables in Docker Compose.

How Can We Use Environment Variables for Secrets in Docker

We often use environment variables to handle sensitive data like API keys or database passwords in Docker. This method helps keep our sensitive information safe. We do not want to hardcode it in our Dockerfiles or application code.

Storing Secrets in Environment Variables

  1. Using Docker Secrets (for Swarm mode): Docker Swarm gives us a simple way to manage secrets. We can create a secret and then use it in our services.

    Create a secret:

    echo "my_secret_password" | docker secret create my_secret -

    Deploy a service using the secret:

    version: '3.8'
    services:
      my_service:
        image: my_image
        secrets:
          - my_secret
    secrets:
      my_secret:
        external: true

    Inside our container, we can find the secret at /run/secrets/my_secret.

  2. Using Environment Variables in Dockerfile: We can also set environment variables in our Dockerfile. But we should be careful. These variables can show up in image layers.

    FROM alpine
    ENV MY_SECRET=my_secret_password
    CMD ["sh", "-c", "echo $MY_SECRET"]
  3. Passing Environment Variables at Runtime: We can use the -e flag with docker run to pass secrets as environment variables when we start a container.

    docker run -e MY_SECRET=my_secret_password my_image
  4. Using Docker Compose for Secrets: In Docker Compose, we can set environment variables in the docker-compose.yml file.

    version: '3.8'
    services:
      my_service:
        image: my_image
        environment:
          MY_SECRET: my_secret_password

Accessing Environment Variables in Containers

To get the environment variables in our application code inside the container, we can use the regular methods from the programming language we choose. For example, in Python:

import os

my_secret = os.getenv('MY_SECRET')
print(my_secret)

Best Practices for Managing Secrets with Environment Variables

  • Do not hardcode secrets in Dockerfiles
  • Use Docker Secrets for important data in production
  • Limit access to the Docker daemon and the secrets
  • Use .env files for local work and do not include them in version control
  • Think about using tools like HashiCorp Vault for more complex needs with secrets

For more detailed tips on managing secrets in Docker, check out How Can I Pass Environment Variables to Docker Containers.

Frequently Asked Questions

1. How can we pass environment variables to Docker containers?

We can pass environment variables to Docker containers using the -e flag with the docker run command. For example, we can run docker run -e MY_ENV_VAR=value my_image. This command will set the MY_ENV_VAR variable inside the container. This way helps us configure our applications without putting sensitive info in our Docker images.

2. How do we set environment variables in a Dockerfile?

To set environment variables in a Dockerfile, we use the ENV instruction. For example, we can add ENV MY_ENV_VAR=value in our Dockerfile. This will create an environment variable called MY_ENV_VAR with the value we want. This method is good for setting default configurations that our application can use when it runs.

3. What is the difference between CMD and ENTRYPOINT in a Dockerfile?

The CMD instruction gives default arguments for the ENTRYPOINT command. It also can tell which command to run when the container starts. On the other hand, ENTRYPOINT sets the main command that runs and ignores any extra command-line parameters. Knowing these differences is important for using environment variables in CMD with Docker.

4. How can we access environment variables inside Docker containers?

Inside a Docker container, we can access environment variables using the printenv command. We can also reference them in our application code. For example, in a shell script, we can use $MY_ENV_VAR to get the value set for MY_ENV_VAR. This ability lets us create dynamic configurations for different environments.

5. How can we use Docker Compose to manage environment variables?

Docker Compose helps us define environment variables in a .env file or right in the docker-compose.yml file under the environment section. For example:

services:
  my_service:
    image: my_image
    environment:
      - MY_ENV_VAR=value

Using environment variables in Docker Compose makes it easier to manage application configurations across many services.

For more info on Docker’s features and best practices, we can read articles like What is Docker and Why Should You Use It? and What are the Benefits of Using Docker in Development?.