here is the docker-compose.yml
I would like to achieve:
version: "3.4"
services:
service1:
image: dorowu/ubuntu-desktop-lxde-vnc
service2:
build:
context: .
environment:
- DISPLAY=[use env variable DISPLAY of service1]
Is there a way in docker compose to tell service2
that the value of env variable DISPLAY
must be the same as the env variable DISPLAY
defined in service1
?
Edit
The DISPLAY
env var is set in dorowu/ubuntu-desktop-lxde-vnc
directly in the Dockerfile.
It’s not a duplicate of Re-using environment variables in docker-compose.yml because the question asked how to write a common env variables for differents services.
In my case I don’t want to explicitly write a common variables (with a .env
file for example) but I want to set the env variable DISPLAY
of service2 to the same value as DISPLAY
in service 1 without having to rewrite it in a .env
file.
For example if I wanted my service2 to have the same DISPLAY
as my host I could write:
version: "3.4"
services:
service1:
image: dorowu/ubuntu-desktop-lxde-vnc
service2:
build:
context: .
environment:
- DISPLAY=$DISPLAY
Now in this case I’m looking for something like:
version: "3.4"
services:
service1:
image: dorowu/ubuntu-desktop-lxde-vnc
service2:
build:
context: .
environment:
- DISPLAY=service1:$DISPLAY
2
Answers
ENV_FILE is what you need. You can share everything between apps by setting up variables in a common file.
.env
Compose has no way of extracting information from an image and republishing it to another container. You clarify that the environment variable is set in the first image’s Dockerfile, and you want its value in the second container; there is no way to do that in Compose.
Of note, there’s also no way to do this in plain Docker. The closest you could come is launching a temporary container to get the environment variable out, but that’s awkward
A similarly awkward
docker inspect
invocation could retrieve the value.But fundamentally, this capability isn’t a standard part of the Docker tool set, and you can’t do it at all in Compose (or other container environments like Kubernetes).
If you’re setting the environment-variable value in Compose then there are tricks like YAML anchors and
env_file:
that can set the same value in multiple places (but not "share them from one container to another" per se). You mention the X Window System$DISPLAY
variable as an example, and for things that refer to other containers it’s likely the server won’t know its own name, so you’d need to set the environment variable directly in the client container in any case.