A build workflow for smaller, safer container images
To reduce a container image while lowering risk, first keep build-only tools and files out of the final image and retain only what the application needs at runtime. Add a trusted base image, secret handling, fewer privileges, regular updates, and image review. A smaller image is not automatically safer: removing a required certificate or native library can break the application.
Decide what the runtime image actually needs
An image should contain the executable, runtime libraries, application configuration, and static files needed in production. Compilers, test tools, development dependencies, the source repository’s .git directory, local caches, and credentials are usually not runtime requirements. But do not assume that certificates, timezone data, fonts, dynamic libraries, or application data files are unnecessary. List requirements from the actual execution paths and outbound connections before removing anything.
Maintain .dockerignore so irrelevant large files and secrets do not enter the build context. Adapt the patterns to the repository and confirm that required build inputs are not excluded.
.git
node_modules
*.log
.env
.env.*This example can also exclude .env.example. Add an explicit exception if a sample configuration is needed, and never put real secrets in the repository or image. Docker documents .dockerignore as a way to exclude files irrelevant to the build context. Docker build best practices
Separate the build stage from the runtime stage
With a multi-stage build, the final stage copies only the required artifacts from earlier FROM stages, leaving compilers and intermediate files out of the runtime image. The following is an illustrative Node.js template. It assumes the project’s package.json scripts and a build output at dist/server.js; it has not been applied or tested against a real project.
# syntax=docker/dockerfile:1
FROM node:22-slim AS build
WORKDIR /srv/app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-slim AS runtime
ENV NODE_ENV=production
WORKDIR /srv/app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build --chown=node:node /srv/app/dist ./dist
USER node
CMD ["node", "dist/server.js"]The builder’s development dependencies and full source tree are not copied into the final stage; the runtime stage receives production dependencies and build output. USER node works only if the selected base image provides that user and file permissions fit the app. Check the user and paths in the chosen base. Native modules also require compatible system libraries and ABI between build and runtime stages. This example assumes the app does not write into /srv/app at runtime; give any writable paths appropriate ownership. Removing packages alone is not enough. Docker’s multi-stage documentation explains how to copy selected artifacts into the final stage. Docker multi-stage builds
Manage layers and build cache together
If a build command creates a file in one layer and removes it in a later layer, the earlier layer may still contain the data even though it is absent from the final filesystem view. When package indexes or temporary artifacts should not remain in the image, install and clean them in the same RUN instruction. However, deleting every cache can slow later builds. Distinguish package caches stored in image layers from build caches that the builder can reuse. See the image-layer guide for how layers and cache reuse work.
For a Debian/Ubuntu-based image, an OS package installation might look like this. Adjust package names and versions to the project, and keep the index refresh and install in one step to avoid reusing an outdated cached index.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/*This command applies only to Debian-family package managers. Follow the corresponding package-manager guidance for Alpine or another distribution. Docker also recommends combining apt-get update and package installation in one RUN instruction and removing unneeded package indexes. Docker build best practices
A smaller base image is not always the better choice
Prefer images from a trusted, reviewable publisher, but check for the libc, certificates, shell, diagnostic tools, patch process, and support period your app needs. Minimal bases such as scratch can fit statically linked programs when you can supply all required files. If required libraries are absent or operators cannot investigate failures, a smaller image may increase operational risk.
A tag is convenient for updates but may later point to different content. Pinning a digest in a deployment helps select the same content, but it can also keep an old vulnerable image in use. Use an approved version or digest and also run a regular review and rebuild process for updates. Kubernetes documents that a digest identifies fixed image content and warns that latest is harder to track and roll back. Kubernetes image documentation
Do not pass build credentials through ARG or ENV; they can persist in the image. Use a BuildKit secret or SSH mount that exposes the value only for the build instruction that needs it. Image signatures and provenance help assess source and integrity; they are separate from evidence that packages have no vulnerabilities. See Docker build secrets and the image-signing guide.
How do you check the build result?
These are example commands for a local Docker environment; they were not run for this article.
docker build --pull -t example-app:review .
docker image inspect example-app:review --format '{{.Size}}'
docker history --no-trunc example-app:review
docker scout quickview example-app:review--pull checks for a fresh base image; --no-cache is a separate option that disables build-step cache and does not itself pull a new base. Compare image size before and after using the same builder and measurement method. Use docker history to find unexpected layers or copied files. If Docker Scout is available, it can report image components and known vulnerability data. A scan depends on its advisory data and package detection; no findings do not prove an image is safe. Docker Scout
Also verify the app’s startup, main requests, certificate validation, file permissions, and shutdown behavior with the built image. If the smaller image fails these checks, do not deploy it; restore the missing runtime dependency or choose a suitable base.
Apply the changes in this order
Record the current image size, layers, package list, and runtime dependencies.
Use `.dockerignore` to keep secrets, caches, and irrelevant files out of the build context.
Separate build tools and outputs with a multi-stage build.
Retain only needed runtime packages and use a non-privileged user where the app supports it.
Check the tag or digest, patch-update process, vulnerability review, and image-signing policy in CI.
Compare size consistently and verify app behavior and recovery steps before deployment.
Summary
Smaller images come from excluding files and dependencies the runtime does not need. Safer image practices also require trustworthy sources, least privilege, secret protection, updates, and verification. Multi-stage builds and cleanup help, but removing files without checking runtime requirements can cause failures. Treat size, vulnerability findings, provenance, and runtime permissions as separate checks.
Sources
[Docker build best practices](https://docs.docker.com/build/building/best-practices/)
[Docker multi-stage builds](https://docs.docker.com/build/building/multi-stage/)
[Docker build secrets](https://docs.docker.com/build/building/secrets/)
[Docker Scout](https://docs.docker.com/scout/)
[Kubernetes image documentation](https://kubernetes.io/docs/concepts/containers/images/)
[Dockerfile guide](https://knowledge.linkspot.net/ko/articles/83427e7d-a9ae-423d-a9ac-862b9bc610d6)
[Container security baseline](https://knowledge.linkspot.net/ko/articles/bb913cb8-08aa-4707-915b-2cc4856eaa04)
[Docker multi-stage build guide](https://knowledge.linkspot.net/ko/articles/de718f32-13ac-4629-9475-668eb027d94b)
Scope: image size, contents, and basic build hygiene for Docker/BuildKit workflows. Official Docker and Kubernetes documentation was checked on 2026-11-23. The Dockerfile and commands are illustrative; no build or scan was performed. No current CVE count, size reduction, or provider-specific support policy was evaluated. Runtime permissions, network policy, and enforcement of image signatures are separate configuration topics.