1. Home
  2. Blog
  3. DevOps

DevOps

Dockerfile Best Practices: Smaller, Faster, Safer Images

Ten Dockerfile best practices that shrink images, speed up builds and close common security gaps, shown on one real Node.js example you can copy and adapt.

9 min read
Dockerfile best practices for smaller, faster and safer Docker images

Key takeaways

  • 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 update and apt-get install in the same RUN, otherwise a cached update layer can install stale package lists.
  • Install only what you need. Use --no-install-recommends and remove the apt lists afterwards.
  • Prefer COPY to ADD. ADD also 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
  • .dockerignore present and excluding .git, node_modules and .env
  • USER set to a non-root account
  • Exec-form CMD or ENTRYPOINT
  • No secrets in ENV, ARG or 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →