In Docker, there are several methods to pass environment variables to containers. These methods can be applied in various scenarios based on the specific use case and security requirements. Below, I will detail each method with specific examples.
1. Using the -e parameter in the docker run command
When using docker run to start a container, you can set environment variables using the -e option. This method is suitable for temporary containers or development environments, as it is intuitive and convenient.
Example:
bashdocker run -e "API_KEY=123456" -d my_image
This command starts a new container with the environment variable API_KEY set to 123456.
2. Using the ENV instruction in Dockerfile
If an environment variable is required by the container at all times, you can set it directly in the Dockerfile using the ENV instruction.
Example:
DockerfileFROM ubuntu ENV API_KEY 123456
Building and running this Dockerfile will create a container that automatically includes the environment variable API_KEY.
3. Using environment variable files (.env files)
For managing multiple environment variables, storing them in a file is often clearer and more manageable. You can create an environment variable file and specify it using the --env-file option when running docker run.
Example:
Create a file named env.list with the following content:
shellAPI_KEY=123456 DB_HOST=localhost
Then run the container:
bashdocker run --env-file env.list -d my_image
This will automatically set the API_KEY and DB_HOST environment variables in the container.
4. Defining environment variables in docker-compose.yml
If you use Docker Compose to manage your containers, you can define environment variables for services in the docker-compose.yml file.
Example:
yamlversion: '3' services: webapp: image: my_image environment: - API_KEY=123456
When starting the service with docker-compose up, the webapp service will include the environment variable API_KEY.
Summary
Based on your specific needs, choose one or multiple methods to pass environment variables to your Docker containers. In practice, you may select the appropriate method based on security considerations, convenience, and project complexity.