In this post, I’ll demonstrate how powerful and flexible the .env
file can be when setting up a compose.yaml
for Docker Compose. This approach allows for easy management of environment variables, making your Docker configurations more dynamic and manageable.
Let’s start with a simple .env
file:
UBUNTU_VERSION=24.04
And a corresponding compose.yaml
file:
services:
test:
image: ubuntu:${UBUNTU_VERSION}
command: ["sh", "-c", "env"]
When you run the Docker Compose stack with the command docker compose up
, you’ll see an output like this:
$ docker compose up
[+] Running 2/1
✔ Network tmp_default Created 0.1s
✔ Container tmp-test-1 Created 0.1s
Attaching to test-1
test-1 | HOSTNAME=f9002b77bc79
test-1 | HOME=/root
test-1 | PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
test-1 | PWD=/
test-1 exited with code 0
However, to make the variables defined in the .env
file available within the Docker container, you need to add a couple of lines to your compose.yaml
file:
services:
test:
image: ubuntu:${UBUNTU_VERSION}
command: ["sh", "-c", "env"]
env_file:
- .env
After updating the compose.yaml
file, run the docker compose up
command again. This time, you’ll notice that the UBUNTU_VERSION
environment variable is now included in the container’s environment:
$ docker compose up
[+] Running 1/0
✔ Container tmp-test-1 Recreated 0.1s
Attaching to test-1
test-1 | HOSTNAME=069e3c4a4413
test-1 | HOME=/root
test-1 | PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
test-1 | UBUNTU_VERSION=24.04
test-1 | PWD=/
test-1 exited with code 0
This is incredibly convenient because maintaining the .env
file allows you to easily manage environment variables across different services without modifying the compose.yaml
file each time. This example clearly illustrates how powerful and useful it is to use .env
files in Docker Compose configurations.
2 thoughts on “The Power of the .env File in Docker Compose”
I appreciate you taking the time to write and share this insightful piece. It was clear and concise, and I found the data to be really useful. Your time and energy spent on this article’s research and writing are much appreciated. Anyone interested in this topic would surely benefit from this resource.
Nice blog here Also your site loads up fast What host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol
Comments are closed.