Handling environment variables in Containers (Docker/Podman)
Learn how to configure environment variables for your services in Containerized environments.
·Jan 14, 2023·
1 min read
Environment variables are an essential way to configure your services. They make it easy to configure services for different environments & deployments.
There are several ways to handle environment variables in containers:
- You can pass them directly to the container at runtime using the
-eflag, like this:
$ docker run -e VAR_NAME=value -e VAR_NAME2=value2 image_name
- You can also set environment variables in the
Dockerfilefor your image. This can be done using the
ENVdirective, like this:
ENV VAR_NAME value ENV VAR_NAME2 value2
- You can use a
.envfile to store your environment variables and pass them to the container at runtime using the
$ docker run --env-file .env image_name
.env file should contain one
VAR_NAME=value pair per line.
POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_PORT=5432 POSTGRES_DB=my-db
- You can also pass environment variables to a container when using
docker-compose. To do this, you can set them in the
environmentsection of the
docker-compose.ymlfile, like this:
version: '3' services: web: environment: - VAR_NAME=value - VAR_NAME2=value2 image: image_name
In Podman, you can use the same flags and methods to handle environment variables.
A full working example of this article can be found below.