Deploying Docker Containers with Environment Variables
When deploying Docker containers, you can pass environment variables to the container at runtime. This allows you to easily configure the container's behavior without having to rebuild the image.
Passing Environment Variables to Containers
You can pass environment variables to a Docker container using the -e
or --env
flag when running the docker run
command. For example:
docker run -e DB_PASSWORD=mypassword my-app
In this example, the DB_PASSWORD
environment variable is set to mypassword
for the my-app
container.
You can also pass multiple environment variables at once:
docker run -e DB_PASSWORD=mypassword -e API_KEY=abc123 my-app
Using Environment Variables in Containers
Once you have passed environment variables to a container, you can access them within the container using the standard shell syntax, such as $VARIABLE_NAME
. For example:
docker run -e DB_PASSWORD=mypassword my-app sh -c "echo The database password is: $DB_PASSWORD"
This will output the value of the DB_PASSWORD
environment variable inside the container.
Passing Environment Variables from a File
Instead of passing environment variables directly on the command line, you can store them in a file and pass the file to the container using the --env-file
flag. This can be useful if you have a large number of environment variables to manage.
Create a file named env.list
with the following content:
DB_PASSWORD=mypassword
API_KEY=abc123
LOG_LEVEL=info
Then, run the container using the --env-file
flag:
docker run --env-file env.list my-app
This will pass all the environment variables defined in the env.list
file to the my-app
container.
By using environment variables when deploying Docker containers, you can easily configure your applications without having to rebuild the container image.