I knew how to set environment variables in a Docker Compose service but I didn’t know how to share. So I’ve written notes for my output.
Background
I had an issue in that I had to set many environment variables in Docker Compose YAML and most of them were shared with some of the services. So I thought there should be a solution to it.
What I did
I used thex-
prefix to reuse variables.
It can be used not only for sharing environment variables but also for sharing functions like volume
and depends_on
Then my docker-compose.yml changed like below.
Before
version: '3.8'
services:
service1:
image: path/to/image1
environment:
- COMMON_ONE
- COMMON_TWO
...other common variables...
service2:
image: path/to/image2
environment:
- COMMON_ONE
- COMMON_TWO
...other common variables...
- NOT_COMMON_ONE
- NOT_COMMON_TWO
After
version: '3.8'
x-common-environment: &common-env
- COMMON_ONE
- COMMON_TWO
...other common variables...
services:
service1:
image: path/to/image
environment:
<<: *common-env
service2:
image: path/to/image2
environment:
<<: *common-env
- NOT_COMMON_ONE
- NOT_COMMON_TWO
Small note. If you have variables with the same name as variables in shell or .env
, you don’t have to set the value ( — COMMON_ONE=${COMMON_ONE}
).
That’s it!