乐闻世界logo
搜索文章和话题

How do you pass environment variables to a Docker container?

1个答案

1

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:

bash
docker 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:

Dockerfile
FROM 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:

shell
API_KEY=123456 DB_HOST=localhost

Then run the container:

bash
docker 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:

yaml
version: '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.

2024年8月9日 13:56 回复

你的答案