Chapter 1 of 6 · 5 practices · 4 min · 4-question quiz
Writing the Dockerfile
How to structure a Dockerfile so the image is small and rebuilds are fast: the base image, stages, instruction order and the build context.
Start: Start from a small, official base image5 practices in this chapter
- 1Start from a small, official base imageThe base image decides most of your image size and most of the vulnerabilities a scanner will find. Pick it on purpose, not by habit.
- 2Use multi-stage builds to keep build tools out of the final imageCompilers, dev dependencies and test tools are needed to build your app, not to run it. Shipping them makes the image bigger and hands an attacker extra tools.
- 3Order instructions so dependency layers stay cachedDocker caches each instruction as a layer and reuses it until something that layer depends on changes. Once one layer is invalidated, every layer after it rebuilds too, so instruction order decides…
- 4Add a .dockerignore file to shrink the build contextEverything in the build context is sent to the builder, and
COPY . .copies all of it into the image. Without a.dockerignore, that includes:node_modulesand build output such asdist; the… - 5Run apt-get update and install in the same RUN stepIf
apt-get updateruns in its own layer, Docker caches it, and later installs use a stale package list. Weeks later that can fail outright or quietly install old versions.
Check yourself on this chapter
4 questions, right here once you are signed in. Your progress is saved as you read.