Combine multiple images using one dockerfile

When you are working on a large project on docker, you need to go through certain phases of the development cycle. Maintaining a different dockerfile for each cycle such as build, release, testing etc. eats up a lot of resources and is highly inefficient when it comes to productivity.

In the later versions of docker, it allows us to use what is called multi-stage Dockerfile with the help of two particular commands - FROM and AS.

We can use multiple FROM commands combined with AS commands in our Dockerfile where the last FROM command will actually build the image. All the FROM commands before that, will lead to the creation of intermediate images which are cached regularly.

The AS command when used with the FROM command allows us to provide a virtual name for our intermediate images.

Let us consider an example below for better understanding.

#We create a base image.
FROM ubuntu AS base

#Install packages
RUN apt-get -y update
RUN apt-get -y vim

#Create intermediate image layer Dependencies
FROM base AS dependencies

#Install dependencies using a requirements file
RUN pip3 install -r requirements.txt

#Create intermediate image layer for Testing
FROM dependencies AS test

#Set your work directory
WORKDIR /usr/src/app

COPY . .

#Build the final image by running the test file
CMD [“python3”, “./”]

As we can see in the above dockerfile, we have created two intermediate images called base and dependencies. The base intermediate image is an ubuntu image and we update it and install vim editor inside it. Using that base image, to create an intermediate image called dependencies, we install certain dependencies for our project which we can define in a separate file called requirements.txt. The final image is created by the test image layer where we define the working directory, copy the files and run the file.

The order of building the images is base, then dependencies and at last test. We also have to note that in case, any of the intermediate images fails to build, the final image cannot be created.

Thus, creating a multi-stage dockerfile helps when you are working on a large scale project development with various phases of development surely helps us track the changes and progress efficiently.