I am trying to work with multiple images from a single Dockerfile. The following succeeds when docker compose build
is run, but I notice in the layers that both images have ENV KEY2=VALUE2
. I am expecting image1 to have ENV KEY1=VALUE1
.
What am I missing?
Dockerfile:
FROM ubuntu:23.04 AS image1
ENV KEY1=VALUE1
FROM ubuntu:23.04 AS image2
ENV KEY2=VALUE2
compose.yaml:
services:
service1:
container_name: container1
build: .
image: image1
service2:
container_name: container2
build: .
image: image2
4
Answers
Added after comment :
Then you better to create two Dockerfiles and use them in
docker-compose
docker-file1.yaml
docker-file2.yaml
You docker-compose file :
The documentation describes the following behavior when you use
image
in the docker compose file:so the
Dockerfile
is built and indeed it is tagged withimage1
, however given the multi-stage build nature of theDockerfile
you end up only with everything following the secondFROM
.Use separate Dockerfiles for the two images.
Environment variables are not shared by default across stages in multi-stage Dockerfiles. However, as others have pointed out in the comments, behaviour is likely different when building via docker compose.
If you intend to share the Dockerfile between the two images, and the only differences between the two are a few variables, you should use the args sub-option:
Dockerfile
Docker Compose
But if the images have different setups, you should use two separate Dockerfiles.
I tested it, and it works.
Please create 2 dockerfiles.
Dockerfile1:
Dockerfile2:
docker-compose.yaml:
To run the containers up, "tail -f /dev/null".
Print screens: