To forward environment variables from your host machine to a Docker container, you can use several methods:
-
Using the -e Flag:
You can pass individual environment variables directly in the docker run command using the -e (or --env) flag:
docker run -e VARIABLE_NAME=value image_name
For example, to set a variable MY_VAR with the value my_value:
docker run -e MY_VAR=my_value image_name
If the environment variable is already set on your host machine, you can pass it without specifying the value:
export MY_VAR=my_value
docker run -e MY_VAR image_name
This approach is useful for passing a few variables but can become cumbersome with many variables.
-
Using an Environment File:
For managing multiple environment variables, you can use an environment file. Create a file (e.g., env.list) with each variable on a new line:
VARIABLE1=value1
VARIABLE2=value2
Then, pass this file to the docker run command using the --env-file flag:
docker run --env-file env.list image_name
This method keeps your command line cleaner and is especially useful for handling sensitive information, as it avoids exposing variables in the command history.
-
Using Docker Compose:
If you're using Docker Compose, you can define environment variables directly in your docker-compose.yml file:
services:
app:
image: image_name
environment:
- VARIABLE1=value1
- VARIABLE2=value2
Alternatively, you can reference an environment file:
services:
app:
image: image_name
env_file:
- env.list
This approach is beneficial for complex applications requiring multiple services and configurations.
By following these methods and best practices, you can effectively manage and forward environment variables to your Docker containers, ensuring a secure and efficient deployment process.