In this tutorial, we will learn how to pass environment variables to Docker containers, allowing you to configure your applications and services with dynamic values.
Using the -e
Option
When running a Docker container, you can pass environment variables using the -e
option followed by the variable name and its value. The general syntax is as follows:
docker run -e "VARIABLE_NAME=variable_value" image_name
Here's what each part of this command means:
-
docker run
: This is the command to run a Docker container. -
-e "VARIABLE_NAME=variable_value"
: This is the option to pass the environment variable to the container. ReplaceVARIABLE_NAME
with the name of your environment variable, andvariable_value
with the value you want to assign to it. -
image_name
: This specifies the Docker image you want to run, such asnginx
,mysql
, or any custom image you've built.
Passing Multiple Environment Variables
To pass multiple environment variables to the container, you can use the -e
option multiple times. For example:
docker run -e "VAR1=value1" -e "VAR2=value2" image_name
This command will set two environment variables, VAR1
and VAR2
, in the container with their respective values.
Using Environment Files
Alternatively, if you have a lot of environment variables to set, you can use an environment file and pass it to the container using the --env-file
option. Create a file (e.g., env_vars.txt
) and define your environment variables in it, one variable per line, in the following format:
VAR1=value1
VAR2=value2
VAR3=value3
Then, run the container with the following command:
docker run --env-file env_vars.txt image_name
Docker will read the variables from the file and pass them to the container.
Checking Environment Variables Inside the Container
To verify that the environment variables are correctly set inside the container, you can log into the container and inspect its environment. Use the following command to open an interactive shell inside the running container:
docker exec -it container_name_or_id sh
Once inside the container, you can use the printenv
command to view all the environment variables:
printenv
You should see the environment variables you passed listed with their respective values.
0 Comment