Dockerfiles: Building Your Own Image

Last time we established that a container is not a tiny virtual machine — it is an ordinary process on the host kernel, fenced off by namespaces, rationed by cgroups, reading its files from a stack of read-only layers. What we never did was make one of those stacks. We pulled images. We did not build any.

Building is where containers stop being something you download and start being something you own. The file that does it is worth learning properly rather than copying off the internet, because very nearly every complaint about Docker being slow, bloated or leaky traces back to a Dockerfile written by someone who did not know what each line costs.

A recipe, not a snapshot

You can build an image without a Dockerfile at all. Start a container from something close to what you want, install your bits by hand, run docker commit, and out comes an image. It works. People do it. It is also how you end up with a four-gigabyte artefact that nobody — including you, six weeks later — can rebuild, audit or explain.

A Dockerfile is the opposite bargain. It is a plain text build script: a list of instructions that, run in order against a known starting point, produce the image. It lives in version control next to the code. It turns up in a diff. Somebody can review it. When the result is wrong you change a line and rebuild, instead of doing archaeology on a binary.

The image is the output, not the source

Treat a built image the way you treat a compiled binary. The Dockerfile and the repository around it are the source of truth; the image is a build artefact you should be able to delete and regenerate without a second thought. If you cannot regenerate it, you do not have a build. You have a pet.

Here is a complete, respectable one:

$ cat Dockerfile
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
CMD ["node", "src/server.js"]

$ docker build -t myapp:1.4.0 .
 => [1/5] FROM docker.io/library/node:22-slim      CACHED
 => [2/5] WORKDIR /app                             CACHED
 => [3/5] COPY package*.json ./                    CACHED
 => [4/5] RUN npm ci --omit=dev                    CACHED
 => [5/5] COPY . .                                 0.1s
 => naming to docker.io/library/myapp:1.4.0

Seven lines. Every one of them is doing something specific, two of them are in that order for a reason we will come to shortly, and the build output is already telling you what the rest of this post is about.

The instructions that matter

There are a couple of dozen Dockerfile instructions. You will use about eight of them.

InstructionWhat it doesWorth knowing
FROMSets the base image that every later layer stacks ontoPin something specific. node:22-slim, never node:latest
WORKDIRSets the working directory for everything after itCreates the directory if it is missing. Use it instead of RUN cd, which does not persist past its own layer
COPYCopies files from the build context into the imagePrefer it to ADD, which also unpacks archives and fetches URLs, usually at the moment you least wanted it to
RUNRuns a command at build time and commits the result as a layerChain related commands with && so you get one layer instead of five
ENVSets an environment variable, at build time and at run timeVisible in docker inspect forever. Not for secrets
EXPOSEDocuments which port the application listens onDocuments. That is the whole of it. It publishes nothing
USERSwitches user for the instructions below it and at run timeDefaults to root if you never set it, which is most images
CMDThe default command, replaceable on the command linedocker run myapp echo hi throws it away entirely
ENTRYPOINTThe command that always runs; CMD becomes its argumentsUse it when the image is one tool. Use CMD alone when the image is one application

Both CMD and ENTRYPOINT accept either a JSON array or a bare string. Use the array. The string form wraps your process in /bin/sh -c, which makes your application a child of a shell, and the shell is then the one receiving the stop signal. Your process never hears about it, Docker waits ten seconds, then kills it outright. Containers that take exactly ten seconds to stop are almost always this, and the fix is a pair of square brackets.

EXPOSE does not expose anything

EXPOSE 3000 adds a line of metadata to the image. It does not open a port, publish a port, or touch a firewall rule. The port becomes reachable when you run the container with -p 8080:3000, and not one moment before. The instruction is useful documentation for whoever meets the image next, and completely inert otherwise.

Every line is a layer

Each instruction that changes the filesystem produces a layer, and Docker caches layers. On a rebuild it walks the Dockerfile from the top asking one question at each step: are the inputs to this instruction identical to last time? While the answer is yes, it reuses the cached layer. The first time the answer is no, that layer is rebuilt — and so is every layer below it, because each one was built on top of the one before. There is no way to rebuild a layer in the middle and keep the rest.

That single rule is the whole game, and it means the order of your instructions decides how long your builds take. Consider the obvious way to write it:

FROM node:22-slim
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "src/server.js"]

Nothing about it is wrong, exactly. COPY . . brings in the entire source tree, so its inputs change the instant you edit any file at all — and it sits above the install. Fix a typo in a comment and the cache breaks at that line, which means npm ci runs again, downloading and compiling every dependency from scratch, to produce precisely the node_modules it produced last time. Which looks like this:

One line of server.js changes. Then: docker build. SOURCE COPIED FIRST MANIFEST COPIED FIRST FROM node:22-slim WORKDIR /app COPY . . RUN npm ci CMD [“node”,”server.js”] FROM node:22-slim WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . CMD [“node”,”server.js”] server.js changed CACHED CACHED REBUILT REBUILT REBUILT CACHED CACHED CACHED CACHED REBUILT REBUILT npm ci runs again npm ci skipped Same app, same dependencies — one extra line, in a different place. You change one line in server.js and run docker build again. Docker reuses layers until the first one whose inputs changed. Copy the dependency manifest before the source, and the install stays cached.
Both Dockerfiles install exactly the same dependencies. The one that copies its dependency manifest before its source code keeps the install cached, so editing the application rebuilds two layers instead of three — and skips the slowest step entirely.

The fix is to copy the thing that describes your dependencies before the thing that changes constantly, and do the install in between:

FROM node:22-slim
WORKDIR /app
COPY package*.json ./          # changes rarely
RUN npm ci --omit=dev          # so this stays cached
COPY . .                       # changes constantly
CMD ["node", "src/server.js"]

One extra instruction, and editing your application now invalidates only the bottom two layers. The dependency install re-runs when your dependencies actually change, and not otherwise. The same principle applies in every ecosystem: requirements.txt before your Python, composer.json and composer.lock before your PHP, go.mod and go.sum before your Go.

Order by volatility

Slowest and least-frequently-changing at the top; fastest and most-frequently-changing at the bottom. Base image, then system packages, then language dependencies, then your own code. It reads slightly oddly to a human, and it is exactly what the cache wants.

What you ship is the whole directory

When you run docker build ., that trailing dot is the build context. Docker packages up everything in that directory and hands the lot over before a single instruction runs. If the directory holds a .git folder with ten years of history, a node_modules from your last local install and two gigabytes of test fixtures, all of it gets packaged — every build, whether any instruction touches it or not.

.dockerignore fixes that, and reads just like .gitignore:

.git
.gitignore
node_modules
npm-debug.log
.env
*.md
tests/fixtures/

Two benefits, and the second one matters more than the first. Builds get faster, because you have stopped shipping a gigabyte of irrelevance for no reason. And COPY . . stops being a loaded gun — because without that .env line, the most natural way to write a Dockerfile copies your local environment file, credentials and all, directly into the image.

Secrets do not belong in layers

Which brings us to the mistake genuinely worth losing sleep over. Say the build needs a credential, so you do the tidy-looking thing:

COPY .env .
RUN ./build-needing-credentials.sh
RUN rm .env                      # all tidy now

It is not tidy. Layers are additive and permanent. That third instruction creates a new layer in which the file is absent; the second layer, still sitting in the image underneath it, still contains the file. Delete it, overwrite it, shred it — the earlier layer is unchanged, and anybody who can pull the image can unpack that layer and read the contents.

Anything that ever entered a layer is still in the image

docker history lists every layer and the instruction that built it. docker save hands you those layers as tar files to pick through at leisure. A secret committed into an image has been published, not stored — so if that image ever reached a registry, rotate the credential. Deleting the tag is not a fix, and neither is a later rm.

Configuration belongs at run time, not build time: pass it with -e, an --env-file, or your orchestrator’s secret mechanism. For the genuinely awkward case where a build really does need a credential — a private package registry, typically — BuildKit offers RUN --mount=type=secret, which makes the value available to that one command and never writes it into a layer.

Two stages, one small image

Most things need more to build than they need to run: a compiler, dev headers, a test framework, a bundler. None of it needs to be in the image you deploy, and all of it is extra weight and extra attack surface if you leave it there. Multi-stage builds let you throw it away.

# ---- build stage: the full toolchain ----
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# ---- runtime stage: only what runs ----
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]

Two FROM lines, so two independent stacks of layers. Only the last one becomes your image; the first exists purely so that COPY --from=build can reach into it and lift out the compiled output. The toolchain, the dev dependencies and your source code never reach the thing you ship — and the cache rules still apply within each stage, which is why the manifest is copied first in both.

Tags are not versions

myapp:latest is not a version. It is a mutable label pointing at whatever was tagged most recently, which makes it the one tag guaranteed to mean something different tomorrow. FROM node:latest in particular is a standing promise that your build will eventually break for reasons entirely unrelated to anything you did.

So tag deliberately, and when it genuinely matters, pin the digest — the content hash of one exact image, which cannot be moved under you:

# loose: "22" moves every time a patch lands
FROM node:22-slim

# better: a specific patch release
FROM node:22.9.0-slim

# exact: the same bytes, forever
FROM node:22-slim@sha256:1a2b3c4d...

In increasing order of how much you trust your future self. The middle one is the right default for most projects; the digest is for the builds that have to be reproducible a year from now.

Do not run as root

If you never write a USER instruction, your process runs as root. Not “root in a sandbox” — uid 0, which inside the container is genuinely root, and on any file shared with the host through a bind mount is root there too, unless the host has been set up to remap it. Plenty of hosts have not been.

The container serving you this page does remap it: the web server inside sees itself as an unprivileged user, and the host sees a high-numbered uid that owns nothing of consequence. That is a property of how the platform underneath was built, though, not something an image can assume about wherever it lands. So declare it yourself:

# many base images already ship an unprivileged user
USER node

# otherwise, make one
RUN useradd --system --create-home --shell /usr/sbin/nologin app
USER app

Put it after the instructions that need to write to the filesystem — installing packages, creating directories — and before CMD. Do that, and if something ever does get out of your application, it lands as a user who cannot install packages, cannot write to the system directories, and cannot do a great deal of anything.

A two-second audit

docker inspect --format '{{.Config.User}}' myapp:1.4.0 prints the user an image will run as. An empty string means nobody ever set one, which means root. Worth running against anything you are about to deploy, including images you did not build.

The one-sentence version

A Dockerfile is a build script, every instruction is a cached layer, and the order you write them in decides both how fast your builds run and how much ends up in the thing you ship. Copy the dependency manifest before the source, keep secrets out of layers entirely, leave the build toolchain behind in an earlier stage, pin what you depend on, and do not run as root.

That gets you one image, built properly. The trouble is that a real application is rarely one container — it is an application, a database, a cache and a reverse proxy, all of which need to find each other, keep their data and start in roughly the right order. Describing that on the command line gets old after about the third docker run. Next in this series: Compose, and one file that describes the lot.