Creating multiple images from a single Dockerfile

1st step: wait until Docker 17.05 (or get the alpha)

Adilson Carvalho
Adilson's Notes
Published in
2 min readJun 23, 2017

--

Soon Docker will allow us to handle on a more elegant way our need for multiple images for the same code depending on the step on our pipeline.

On pipelines, go read this great article about it:

Nowadays most of us create several Dockerfiles to attend each need (production, staging, testing, etc.) and sometimes we just keep it all in one wasting resources by carrying with us items we don't need. Other option is to use the Build Container pattern.

The multi-stage Dockerfile

The new Docker version will allow us to have multi-stage images by extending two commands: FROM and COPY.

Now you'll be able to have multiple FROM commands on the same Dockerfile. The last one will actually produce the image while the others will just create the intermediate images. While no final image got produced, all the intermediate layers get cached.

The FROM will allow you to name one specific build by using the AS keyword. It'll give to the current image a logical name that will be acessible later on commands like COPY --from=<image_AS_name|image_number>.

The image numbers, as virtually all collections on the computing fields, start on zero.

An example

Consider the following Dockerfile to illustrate how it works:

On this file we will have three intermediate images: base, dependencies and test. The final image will be produced by the final FROM defined on release.

Each one will be built, following the following order: base -> dependencies -> test -> release. If any step of the build fails, no final image is generated.

This is just perfect to suit our CI needs. It'll be just a matter of building the image. If it made it, we can store on our registry and proceed to our deployment flow.

Thanks Docker Team for this new feature that will simplify our development pipeline.

--

--

Adilson Carvalho
Adilson's Notes

Curious developer, founder member of GURU-PR, fountain pen addict, husband, father.