0
0
DockerHow-ToBeginner · 3 min read

How to Use docker run -e to Set Environment Variables

Use docker run -e VARIABLE=value to set environment variables inside a Docker container at runtime. This lets you customize container behavior without changing the image. You can specify multiple -e options to set several variables.
📐

Syntax

The docker run -e option sets environment variables inside the container. You write it as -e VARIABLE=value. You can add many -e options to set multiple variables.

  • docker run: Command to start a container.
  • -e: Flag to set an environment variable.
  • VARIABLE=value: The name and value of the environment variable.
  • image: The Docker image to run.
bash
docker run -e VARIABLE=value image
💻

Example

This example runs an alpine container and sets the environment variable GREETING to Hello. The container prints the value of GREETING using echo.

bash
docker run --rm -e GREETING=Hello alpine sh -c 'echo $GREETING'
Output
Hello
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to quote values with spaces or special characters.
  • Using = without a value, which sets an empty variable.
  • Trying to set variables without -e, which won't work.

Example of wrong and right usage:

bash
docker run --rm -e GREETING=Hello World alpine sh -c 'echo $GREETING'
# Wrong: 'World' is treated as a command, not part of the variable

docker run --rm -e "GREETING=Hello World" alpine sh -c 'echo "$GREETING"'
# Right: Quotes keep the value together
Output
Hello Hello World
📊

Quick Reference

OptionDescriptionExample
-e VARIABLE=valueSet environment variable inside container-e GREETING=Hello
--env-file fileSet multiple variables from a file--env-file env.list
--rmRemove container after exit--rm
imageDocker image to runalpine

Key Takeaways

Use -e VARIABLE=value to pass environment variables to Docker containers.
Quote values with spaces or special characters to avoid errors.
You can specify multiple -e options to set many variables.
Use --rm to clean up containers after they exit.
Environment variables customize container behavior without changing the image.