How do I pass environment variables to Docker containers? | by Harold Finch | Nov, 2024

To pass environment variables to Docker containers, there are several methods you can use. Here are the most common approaches:

You can set environment variables directly in the command line when starting a container using the docker run command.

docker run -e VAR_NAME=value my_image

You can also set multiple variables by repeating the -e flag.

docker run -e VAR1=value1 -e VAR2=value2 my_image

If you have many environment variables, it’s cleaner to store them in a file. Create a file named .env (or any name you choose) and add your variables in the following format.

VAR1=value1
VAR2=value2

Then, use the --env-file option to pass this file to your container:

docker run --env-file .env my_image

If you are using Docker Compose, you can define environment variables in your docker-compose.yml file. You can set them directly under the service definition.

version: '3'
services:
my_service:
image: my_image
environment:
VAR1: value1
VAR2: value2

Alternatively, you can specify an env file in the docker-compose.yml

version: '3'
services:
my_service:
image: my_image
env_file:
- .env

While you cannot directly pass environment variables during the build phase using the docker build command, you can define default values in the Dockerfile using the ENV instruction.

FROM alpine
ENV VAR1=value1

This sets VAR1 with a default value that can be overridden at runtime.

For orchestration tools like Docker Swarm or Kubernetes, environment variables can be defined in the service or pod configurations. For instance, in Kubernetes, you can define environment variables in your pod spec.

apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my_image
env:
- name: VAR1
value: value1

Each method has its use case, and you can choose based on your specific needs and the context in which you’re working. For example, using the --env option is suitable for single containers, while Docker Compose or orchestration tools are better for complex applications with multiple services.

For further reading and more detailed examples, you can refer to the Docker documentation on environment variables and the Docker Compose documentation.

Leave a Comment

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

Scroll to Top