Bitpath

Boss lesson · Unit 02

Small and safe

One image cut down: slim base, two stages, no root, a pinned base

13 exercisesabout 3 min

What you practise

  • Multi-stage builds, slim base images, running as a non-root user, pinning versions
  • An image cut down step by step

Try a question from this lesson

Pick one

Every server downloads an image before running it. An image holds an app plus a C compiler the app never calls. What does removing the compiler change?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The image to cut down

This Dockerfile works, and it has four problems.

The full python:3 base carries compilers and tools the app never uses. The app runs as root. The base tag will point at a different image one day. And every code edit reinstalls the packages.

The rest of this lesson fixes them one at a time.

Dockerfile
FROM python:3
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

Concept

Two stages

A Dockerfile may have several FROM lines. Each one starts a new stage with a fresh filesystem. AS gives a stage a name.

COPY --from=build copies files out of the stage named build. Only the last stage becomes the image; the others are left behind.

Dockerfile
FROM python:3 AS build
RUN python -m venv /venv
COPY requirements.txt .
RUN /venv/bin/pip install \
  -r requirements.txt

FROM python:3-slim
COPY --from=build /venv /venv

Concept

Not root

Unless told otherwise, the process in a container runs as root, user ID 0.

Namespaces still fence it in. But root can change any file the container can reach, and if a bug lets it out of the fence, it is root outside too.

USER switches the user for every later step and for the running container.

Dockerfile
RUN useradd -m app
USER app

9 more exercises in the app

  • 4× multiple choice
  • 1× fill the blanks
  • 2× type the answer
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy