A smaller Docker image can download faster, start with less overhead, and reduce the amount of software that must be reviewed for security. This reusable workflow shows how to optimize a Dockerfile, scan the result, preserve useful build caches, run safely as a non-root user, and diagnose failed builds without guessing.
Overview
Docker image optimization is not just a size competition. A good production image contains the runtime and application files it needs, excludes build-only material, uses a defensible base image, and can be reproduced and inspected by your team. Security scanning is more useful when it is paired with this supply-chain discipline rather than treated as a final checkbox.
Start by recording a baseline. Note the image size, build duration, startup time, runtime memory behavior, and current vulnerability findings. Then make one meaningful change at a time. This makes it easier to tell whether a smaller image still behaves correctly and whether a scan result changed because of your Dockerfile, your base image, or an updated vulnerability database.
A typical optimization sequence is:
- Reduce the build context with a precise
.dockerignorefile. - Separate compilation or dependency installation from the runtime image.
- Order Dockerfile instructions to preserve safe cache reuse.
- Use a suitable, maintained, and deliberately selected base image.
- Remove unnecessary packages and temporary files from the final stage.
- Run the application with the least privilege it needs.
- Scan both the image and the source dependencies in CI.
- Test startup, health checks, configuration, and application behavior.
For related quality gates, connect this process with a pre-commit automation workflow and document the image's runtime contract alongside your API documentation.
Checklist by scenario
When the image is too large
- Inspect the build context. Exclude source-control metadata, local dependencies, test output, logs, editor files, secrets, and other files that are not required by the build.
- Use a multi-stage Docker build. The first stage can contain compilers, package managers, headers, and test tools; the final stage should copy only the compiled application and required runtime assets.
- Install only production dependencies in the runtime stage where the ecosystem supports that distinction.
- Combine related package installation and cleanup in the same
RUNinstruction when temporary package indexes or archives would otherwise remain in an earlier layer. - Review large files with a layer inspection tool such as Dive. Look for duplicated application files, package caches, build output, and accidentally copied directories.
# syntax=docker/dockerfile:1
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
The exact base-image family and dependency command should match the application. The important pattern is that build tools and intermediate files remain outside the final stage.
When the image has security findings
- Identify whether a finding belongs to the operating-system packages, the application dependency tree, or a copied artifact.
- Confirm the affected package is present in the final image, not only in an abandoned build stage.
- Prefer a maintained base image appropriate to the runtime. Treat a minimal image as a design choice, not an automatic security guarantee.
- Pin image references according to your reproducibility policy. A digest can make a build deterministic, while an explicit update process keeps that digest from becoming stale.
- Set severity thresholds and exception rules with the security owner. Do not silently ignore a finding because it is inconvenient; record the reason, scope, and review date.
- Scan before publishing and again in the registry or deployment path when that integration is available.
When builds are slow
- Copy lockfiles and manifest files before the rest of the source code so dependency installation can be reused when application code changes.
- Use BuildKit features and cache mounts where they are supported by your build environment and do not expose credentials.
- Keep cache keys understandable. A cache that reuses stale inputs can create confusing or unsafe results, so verify lockfiles and relevant build arguments are included in the dependency step.
- Measure the difference between local and CI builds. A local cache may hide a slow or poorly configured CI workflow.
When a build or container fails
- Read the first meaningful error, not only the final exit code.
- Build with plain progress output when the default display hides command details.
- Temporarily inspect an intermediate stage or replace the entrypoint with a shell to verify files, permissions, environment variables, and working directories.
- Check architecture assumptions, executable permissions, native modules, certificate stores, and dynamically linked libraries.
- Separate build-time variables from runtime secrets. Do not bake credentials into layers, arguments, or copied configuration files.
Tool comparison
| Tool or approach | Best use | What to verify |
|---|---|---|
| Docker Scout | Docker-oriented image analysis and supply-chain visibility | Repository support, policy configuration, and how findings map to your release process |
| Trivy | Flexible scanning of images, filesystems, repositories, and related targets | Scanner version, database freshness, exit-code rules, and CI output format |
| Grype | Vulnerability matching for container images and software bills of materials | Image source, SBOM workflow, severity handling, and exception process |
| Dive | Understanding layers and locating unnecessary image content | Whether the apparent waste is in the final image or only an intermediate layer |
| BuildKit | Efficient builds, improved output, and cache-aware workflows | Builder configuration, cache boundaries, and secret handling |
| Registry scanning | Checking images close to publication and deployment | When scans run, which tags are covered, and how results block or permit releases |
These tools overlap, but they are not interchangeable. Use a layer-analysis tool to reduce image content, a vulnerability scanner to identify known issues, and a build system to make the process repeatable.
What to double-check
Dockerfile review checklist
- Context: Is
.dockerignorepresent, reviewed, and free of accidental secret exclusions that could hide required inputs? - Stages: Does the final stage copy only runtime files rather than the entire build workspace?
- Ordering: Are stable dependency manifests copied before frequently changing source files?
- Base image: Is the chosen image appropriate for the runtime, architecture, and operational debugging needs?
- Identity: Does the process run as a non-root user, and are ownership and writable directories configured explicitly?
- Configuration: Are ports, health checks, environment variables, and graceful shutdown behavior documented?
- Secrets: Are credentials excluded from the image, build arguments, logs, and cache?
- Reproducibility: Are lockfiles used, image updates intentional, and build inputs visible to reviewers?
Record results in a small optimization worksheet:
| Revision | Image size | Build time | Startup time | Findings | Behavior notes |
|---|---|---|---|---|---|
| Baseline | ___ | ___ | ___ | ___ | ___ |
| After change | ___ | ___ | ___ | ___ | ___ |
Do not accept a smaller image that loses certificates, timezone data, native libraries, diagnostic tools required by your incident process, or application files. Validate the container in an environment that resembles production.
Common mistakes
- Using a smaller base image without testing: Minimal images can omit shells, certificate stores, compatibility libraries, or debugging utilities that your application expects.
- Copying the whole repository: A broad
COPY . .can include local dependencies, secrets, test artifacts, and unnecessary history unless the context is controlled. - Installing and removing packages in separate layers: Deleting files later does not necessarily remove their earlier layer contents from the image history.
- Running as root by default: A container boundary is not a reason to grant more privileges than the process needs.
- Scanning only at release time: Late feedback makes remediation expensive. Add a practical scan earlier, then repeat it near publication.
- Treating every finding as identical: Review reachability, package presence, exploitability, environment, and available fixes while preserving a documented policy.
- Chasing size at the expense of operations: A modestly larger image may be preferable if it improves reliability, observability, or safe incident response.
When to revisit
Revisit this workflow whenever you create a service, change its language runtime, upgrade a base-image family, modify dependency installation, or move builds between local and CI environments. Repeat the review after a significant Dockerfile syntax or BuildKit change, a scanner or registry integration update, or a new vulnerability affecting a package in your image.
A practical recurring pass can be brief: rebuild from a clean context, inspect the layer report, run the configured scanners, compare the worksheet with the previous release, and test startup as the configured non-root user. Review open exceptions and their owners, then update the base-image and dependency plan.
Before merging a Dockerfile change, ask: Did the final image get smaller or more purposeful? Can I explain every layer? Are the findings understood and handled? Does the container still start, serve traffic, shut down cleanly, and expose no unnecessary privilege? If the answer is yes, record the measurements and make the same checks part of the next release review.