32

A new docker feature is to do something like this in the dockerfile

FROM php7-fpm as build
...

FROM build AS test
...

FROM test AS staging
...

As far as i know, the last FROM statement marks the final output image. How is it possible to have two final images from one intermdiate image?

Like

...
FROM build AS test
...
FROM test AS staging
...
FROM test AS prod

Test, staging and prod should not be discarded. I want to check in them into the repository.

Jim Panse
  • 2,220
  • 12
  • 34

1 Answers1

35

You can stop the build at a certain stage and tag them as you want.

docker build --target test -t starx/test:latest .
docker build --target staging -t starx/staging:latest .
docker build --target prod -t starx/prod:latest .

This way, you have different images and you can push each image individually.

Starx
  • 77,474
  • 47
  • 185
  • 261
  • 1
    Ok but this is not possible with docker-compose at all? I mean, i can not write a docker-compose.yml for test, prod, dev and so on, doing this build steps? So i suppose to get my CI to do the dings manually with docker build and so on ... – Jim Panse Feb 28 '18 at 13:23
  • 2
    Oh ... i think i got it ... since docker-compose 3.4 its possible to set a target stage ... thats what i need! Thank you – Jim Panse Feb 28 '18 at 13:30
  • 1
    While this works I would *not* use it to build distinct images for different environments. This goes against the principles [build once, deploy anywhere](https://blog.openshift.com/build-once-deploy-anywhere/) and against [dev-prod-parity](https://12factor.net/dev-prod-parity). A more valid usecase for this would consist of providing an application on different base-distros (`starks:alpine` / `starks:stretch`) – Fabian Braun Dec 07 '18 at 14:56
  • 1
    @fab Using another base image is in my opinion basically the same as installing individual packages in my docker file. Base images can also vary in software, so there is no difference where this is done. Following your statement you would (for example) either have a dev environment with no debugging tools installed or you have a prod image with debugging tools installed. Both cases are no usable in real use cases. I think, equalizing the different stages as much as possible is a good approach but not applicable for every piece of installed software ... – Jim Panse Feb 13 '19 at 08:47
  • This is an important scenario when debugging languages that don't carry a debugger instance. For instance, in Golang, you need Delve debugger and the source-code in an image to debug it from a docker container... I would not provide the debugger in the same production image, but I could certainly always produce 2 images from the same source-code for the 2 different purposes, saved with 2 different tags :) If needed, I can just switch the deployment with the debug tag and bingo, I'm on a different image for pre-production from the same source. – Marcello DeSales Feb 02 '21 at 16:23