The docker run --env-file
command is a useful feature in Docker that allows users to specify environment variables for a container using a file. This command enhances manageability and security by enabling the storage of environment variables in a separate file, rather than directly in the command line or Dockerfile.
Usage:
To use this command, create a plain text file where each line contains an environment variable in the format KEY=VALUE
. For example:
DATABASE_USER=root
DATABASE_PASSWORD=secret
API_KEY=123456
You can then run a Docker container using these environment variables with the following command:
docker run --env-file /path/to/envfile myimage
Benefits:
Simplicity: Easily manage multiple environment variables in a single file.
Security: Avoid exposing sensitive information like passwords or API keys in shell history or command logs.
Portability: Share environment configuration across different environments (development, staging, production) by maintaining different
.env
files.
Example:
docker run --env-file ./myenv.list ubuntu bash -c "echo $DATABASE_USER"
This command will run an Ubuntu container and print the value of DATABASE_USER
specified in the myenv.list
file.
Using --env-file
is an effective practice for organizing and maintaining environment variables for your Docker containers, especially in complex deployment scenarios.