MagneticNeedle@stilllearning:~/blog$ cat adventures-with-docker-multistage-build.md

Adventures With Docker Multistage Build

6 min read 1,080 words by Vibhakar "Gala" Solanki
table of contents

I thought damm a lot of users must have uploaded content only to find out that the docker images were taking up all the space,

This week I dived into the fascinating world of multi-stage docker build

The Problem#

In https://bfportal.gg i use a relatively simple stack,

#wagtail (a cms that runs on #django ) + #docker + #tailwind.

Then one day I woke up to an alert on #datadog that almost all of the disk space on the VPS has been used,

so I did an image prune and thought the size of the images must be quite big to fill up all the space

lo and behold it was 2 gigs for each image ๐Ÿ’€ ( no wonder my poor VPS was all full )

so I went on looking for how to reduce the size of the image.
it was docker multi-stage builds,

At this point i had this good ol’ dockerfile ( Click to expand )
dockerfile
 1# Use an official Python runtime based on Debian 10 "buster" as a parent image.
 2FROM python:3.11-slim-buster as dev
 3
 4# Add user that will be used in the container.
 5RUN useradd --create-home wagtail
 6
 7# Port used by this container to serve HTTP.
 8EXPOSE 8000
 9
10# Set environment variables.
11# 1. Force Python stdout and stderr streams to be unbuffered.
12# 2. Set PORT variable that is used by Gunicorn. This should match "EXPOSE"
13#    command.
14ENV PYTHONUNBUFFERED=1 \
15    PORT=8000 \
16    PYTHONDONTWRITEBYTECODE=1 \
17    PATH="${PATH}:/home/wagtail/.local/bin" \
18    USER="wagtail"
19
20# Install system packages required by Wagtail and Django.
21RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \
22    build-essential \
23    curl \
24    libpq-dev \
25    libmariadbclient-dev \
26    libjpeg62-turbo-dev \
27    zlib1g-dev \
28    libwebp-dev \
29    software-properties-common \
30    zip \
31    unzip \
32    git \
33    npm \
34    && rm -rf /var/lib/apt/lists/* /usr/share/doc /usr/share/man \
35    && apt-get clean
36
37RUN npm install [email protected] -g && \
38    npm install n -g && \
39    n 18.8.0
40
41# Install the application server.
42RUN pip install "gunicorn==20.0.4"
43
44# Install the project requirements.
45COPY requirements.txt /
46RUN pip install -r /requirements.txt
47
48# Use /app folder as a directory where the source code is stored.
49WORKDIR /app
50
51# Set this directory to be owned by the "wagtail" user. This Wagtail project
52# uses SQLite, the folder needs to be owned by the user that
53# will be writing to the database file.
54RUN chown wagtail:wagtail /app
55
56# Copy the source code of the project into the container.
57COPY --chown=wagtail:wagtail . .
58
59# Use user "wagtail" to run the build commands below and the server itself.
60USER wagtail
61
62FROM dev as final
63
64RUN python manage.py tailwind install --no-input;
65RUN python manage.py tailwind build --no-input
66RUN python manage.py collectstatic --noinput --clear

Ugly rht ? ๐Ÿฅฒ
Its basically this

A traditional dockerfile
A traditional dockerfile

The Solution#

So i started with separating the tools from dependencies, there were two clear things that i can separate,

  1. Python Virtual Environment
  2. Node binary

So i made two separate images for each

Python#

In this project i now use poetry, so if you want a reliable way to install poetry in a docker image, here you go

dockerfile
 1FROM python:3.11-buster as builder
 2RUN pip install poetry==1.5.1
 3ENV POETRY_NO_INTERACTION=1 \
 4    POETRY_VIRTUALENVS_IN_PROJECT=1 \
 5    POETRY_VIRTUALENVS_CREATE=1
 6
 7WORKDIR /venv
 8RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends git
 9RUN touch README.md
10
11COPY ["pyproject.toml", "poetry.lock", "./"]
12RUN poetry config installer.max-workers 10
13RUN poetry install --without dev --no-root --no-cache

gave it the name builder so that i can later take advantage of COPY --from=, next up was

Node#

dockerfile
16FROM node:latest as node_base
17RUN echo "NODE Version:" && node --version
18RUN echo "NPM Version:" && npm --version

( PS: why is it so hard to install node in debian images ? making a separate image is sooo much easier )

Now that we have our base images ready we can take advantage of multistage builds

The docker image is then split into two parts :

  • Dev is for local development and contains npm and tailwind binaries
  • Final is for production an i remove the node_modules folder from it to save space

( Previously we only had final :x )

dev#

dockerfile
20FROM python:3.11-slim-buster as dev
21
22WORKDIR /app
23RUN useradd --create-home wagtail
24
25# Port used by this container to serve HTTP.
26EXPOSE 8000
27# Install system packages required by Wagtail and Django.
28RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \
29    build-essential \
30    libpq-dev \
31    libmariadbclient-dev \
32    libjpeg62-turbo-dev \
33    zlib1g-dev \
34    libwebp-dev \
35    curl \
36&& rm -rf /var/lib/apt/lists/*
37# Set environment variables.
38# 1. Force Python stdout and stderr streams to be unbuffered.
39#    command.
40ENV PYTHONUNBUFFERED=1 \
41    PORT=8000 \
42    PYTHONDONTWRITEBYTECODE=1 \
43    USER="wagtail" \
44    VIRTUAL_ENV=/venv/.venv
45
46ENV PATH="${VIRTUAL_ENV}/bin:${PATH}:/home/wagtail/.local/bin"
47COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
48
49
50COPY --chown=wagtail:wagtail --from=node_base /usr/local/bin /usr/local/bin
51COPY --chown=wagtail:wagtail --from=node_base /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/npm
52COPY ./bfportal ./
53RUN chown -R wagtail:wagtail /app
54USER wagtail
55RUN npm install

the important lines are 46 - 51 , in these line we take full advantage by copying only the things we need ๐Ÿ˜.

then we finally move onto final stage

Final#

dockerfile
61FROM dev as final
62
63RUN npx tailwindcss -i ./bfportal/static/src/styles.css  -o ./bfportal/static/css/bfportal.css --minify
64RUN python manage.py collectstatic --noinput --clear  -i static/src/*

Now by using buildx ( docker buildx build --target=final ) one day and a few hours of head-scratching later I was able to bring the size of the image down to just 600MB ๐Ÿ˜ฎ .

To my understanding we did this

A Multi Stage Docker Build
A Multi Stage Docker Build

now all my CI/CD pipelines for bfportal.gg are super fast
( it was around 7 mins before, now it’s < 3 mins ) all thanks to docker โค๏ธ

Further Optimizations#

  • Make use of python-alpine image to have even smaller final image size
  • Find better way to write file so that we can have less layers and more caching

Conclusion#

  • Must use buildx for faster build times and better cache
  • Copy only the final compiled tools from a base image
  • MUST REMOVE node_modules IN THE END

All in all I find docker to be a awesome technology :) , Have a good day

PS : Let me know if you have any ideas how to make it better :), you can find me at discord or twitter (gala_vs)

[suggest changes]