Managing and Using Environment Variables
Accessing Environment Variables in Containers
Once you have defined environment variables in your Dockerfile, you can access them inside the running container using the standard shell syntax. For example, in a Bash script, you can access the value of the DB_HOST
environment variable like this:
echo "Database host: $DB_HOST"
You can also use environment variables in your application code, depending on the programming language and framework you are using.
Overriding Environment Variables at Runtime
When you run a Docker container, you can override the environment variables defined in the Dockerfile using the --env
or -e
flag. This allows you to easily customize the behavior of your container without having to rebuild the image.
docker run -e DB_HOST=192.168.1.100 -e DB_PASSWORD=newpassword myapp
In this example, the DB_HOST
and DB_PASSWORD
environment variables are overridden at runtime, taking precedence over the values defined in the Dockerfile.
Managing Environment Variables with Docker Compose
If you're using Docker Compose to manage your application, you can define environment variables in the environment
section of your docker-compose.yml
file. This allows you to centralize the configuration for your entire application stack.
version: "3"
services:
web:
image: myapp
environment:
DB_HOST: mysql
DB_PORT: 3306
DB_USER: myuser
DB_PASSWORD: secret
mysql:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: secret
In this example, the environment variables for the web
service are defined in the environment
section, and the mysql
service also has its own environment variables defined.
graph TD
A[Docker Compose] --> B[Environment Variables]
B --> C[Docker Containers]
C --> D[Applications]
By managing environment variables in this way, you can easily scale your application, swap out services, and maintain consistent configuration across different environments.