- Order instructions from least to most frequently changed so Docker reuses cached layers.
- Use a small, pinned base image and multi-stage builds to keep tools out of the final image.
- Add a
.dockerignore, run as a non-root user and never bake secrets into layers. - Rebuild regularly and scan images in CI, because base images collect new vulnerabilities over time.
A Dockerfile that works is easy to write. A Dockerfile that builds in seconds, produces a small image and does not run as root takes a few more habits. These Dockerfile best practices are those habits, in the order that gives the biggest payoff.
Instead of a list of rules, we will fix one realistic Dockerfile step by step. The rules come from Docker’s own building best practices guide, and I have added the testing angle that QA teams care about.
New to containers? Start with our Docker tutorial for beginners, then return here.
A typical Dockerfile that ignores Dockerfile best practices
Here is what many first Dockerfiles for a Node.js app look like:
FROM node:latest
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD npm start
It runs, but it has at least six problems. The base tag floats, any source edit invalidates the dependency install, the build context may include node_modules and .git, the image ships dev tools, the app runs as root and the shell form of CMD hides signals from your process. Let us fix them one by one.
1. Choose a small, pinned base image
latest changes without warning, so a build that passed yesterday can fail today. Pin a specific version, and prefer a slim or minimal variant when your app does not need a full operating system.
FROM node:22-slim
Docker’s guidance also suggests pinning by digest (image@sha256:...) when you need fully repeatable builds, with a process to update that digest. Check the official Node image page for the tags that are currently supported rather than copying a version from a tutorial.
2. Order instructions for the build cache
Docker caches each instruction as a layer. When one layer changes, every layer after it is rebuilt. So copy the files that change rarely first, and your source code last. The build cache documentation explains the invalidation rules in detail.
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
Now editing a source file reuses the cached npm ci layer, and the build drops from minutes to seconds. For package managers you can go further with a BuildKit cache mount, for example RUN --mount=type=cache,target=/root/.npm npm ci, which keeps the download cache between builds.
3. Use multi-stage builds
If you adopt only one of these Dockerfile best practices, make it this one.
Build tools, compilers and dev dependencies are needed to build the app, not to run it. A multi-stage build uses one stage to build and a second, clean stage to run, copying across only the result.
# ---- build stage ----
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# ---- runtime stage ----
FROM node:22-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
The final image holds only production dependencies and compiled output. Smaller images pull faster in CI and expose fewer packages to vulnerability scanners. The same pattern works for Go, Java and compiled front ends.
4. Add a .dockerignore file
Everything in the build context is sent to the builder. Without a .dockerignore, that includes .git, local node_modules and sometimes .env files. Create one next to the Dockerfile:
.git
node_modules
npm-debug.log
Dockerfile
.dockerignore
.env
*.md
coverage
playwright-report
This speeds up every build and stops secrets from sneaking into COPY . ..
5. Run as a non-root user
By default processes in a container run as root. If an attacker breaks into the app, root inside the container is a much better starting point than an unprivileged user. Official Node images already include a node user, so USER node is enough. For other bases create one:
RUN groupadd --system app && useradd --system --gid app app
USER app
Make sure the files the app must write are owned by that user, for example with COPY --chown=node:node . ..
6. Write RUN, COPY and CMD carefully
Small instruction habits are part of any list of Dockerfile best practices.
- Chain related commands. Run
apt-get updateandapt-get installin the sameRUN, otherwise a cached update layer can install stale package lists. - Install only what you need. Use
--no-install-recommendsand remove the apt lists afterwards. - Prefer COPY to ADD.
ADDalso unpacks archives and fetches URLs, which is rarely what you intend. - Use exec form
CMD ["node", "server.js"]. The shell form wraps your app in/bin/sh, so signals like SIGTERM may never reach it and containers stop slowly. - Sort multi-line arguments alphabetically so reviews and merges are easier.
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
Secrets: never use ENV or COPY for passwords or tokens. They stay in the image history. Use BuildKit secret mounts for build-time secrets and runtime environment variables for the rest.
7. Build, test and scan in CI
Automation is where Dockerfile best practices stay enforced instead of forgotten.
A Dockerfile is code and needs the same checks. Build it on every pull request, run your tests against the built image and lint it with a tool such as hadolint. Rebuild with docker build --pull on a schedule so you pick up patched base images. Our GitHub Actions CI/CD guide shows how to wire this up, and running Playwright tests with GitHub Actions covers the browser test step.
Testers can add quick checks that catch regressions in the image itself:
docker build -t myapp:test .
docker run --rm myapp:test id -u # should not print 0
docker image ls myapp:test # compare size between builds
docker run --rm -p 3000:3000 myapp:test # then hit /health
Dockerfile best practices checklist
Print this list and review each Dockerfile against it before merging.
- Base image pinned to a specific version (or digest) and as small as practical
- Dependency files copied and installed before application code
- Multi-stage build separating build tools from the runtime image
.dockerignorepresent and excluding.git,node_modulesand.envUSERset to a non-root account- Exec-form
CMDorENTRYPOINT - No secrets in
ENV,ARGor copied files - Image built, tested and scanned in CI, and rebuilt regularly
Keep Dockerfiles in version control and review them like code; our Git tutorial for beginners covers the basics.
Final thoughts
Good Dockerfile best practices come down to a few repeatable moves: pin the base, order layers for the cache, build in stages, ignore what you do not need and drop root. Apply them to one image this week, measure the build time and size before and after, and then make the pattern your team’s template.
Frequently asked questions
What are the most important Dockerfile best practices?
Use a small pinned base image, order instructions for caching, use multi-stage builds, add a .dockerignore, run as a non-root user and keep secrets out of the image.
Why should I avoid the latest tag in a Dockerfile?
The latest tag changes over time, so builds are not repeatable. Pin a version or a digest so the same Dockerfile gives the same base every time.
How do multi-stage builds make images smaller?
They build in one stage and copy only the finished output into a clean final stage, so compilers and dev dependencies never reach the runtime image.
Should I use CMD in shell form or exec form?
Use exec form, for example CMD [“node”,”server.js”], so your process receives signals directly and containers stop cleanly.
Is COPY or ADD better in a Dockerfile?
Prefer COPY. ADD can also fetch URLs and unpack archives, which can surprise you, so use it only when you need those features.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.