How to share environment variables in Docker Compose services

Ats
2 min readSep 4, 2023

--

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.

Photo by Venti Views on Unsplash

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!

--

--

Ats
Ats

Written by Ats

I like building something tangible like touch, gesture, and voice. Ruby on Rails / React Native / Yocto / Raspberry Pi / Interaction Design / CIID IDP alumni

No responses yet