Using multi-stage docker containers in CI

6 Mar 2019

Multi-stage builds are very useful to optimize usage of Dockerfiles for CI and for development process. You can make multiple stages using FROM statements, inherit them by name (given with as name statement) or selectively copy artifacts from one stage to another.

You can see official documentation for example about using multi-stage builds for copying artifacts.

But one of the my favourite use-case is dividing Dockerfile on stages for different build environments, like test, dev, prod and so on, like this:

FROM python:3.6-alpine3.9 as builder
ADD requirements.txt /app/
RUN pip3 install --upgrade -r requirements.txt

FROM builder as test
ADD dev-requirements.txt /app/
RUN pip3 install --upgrade -r dev-requirements.txt
CMD [ "python", "./" ]

FROM builder as deploy
ADD . /app
CMD [ "python", "./" ]

Next we can build image from test, deploy or even builder stage:

> docker build --target test --tag tester

If you find something wrong in this post fill free to create issues here.