A secure Dockerfile starts from a small, trusted base pinned by digest, keeps build tools and credentials out of the final stage, and runs the application as a non-root user with an exec-form entrypoint. Most container image risk is decided before any scanner runs, in the dozen or so lines that describe how the image is built. A secret passed as a build argument, a base image tag that silently moves, or a compiler left in the production image will all ship, whatever controls sit downstream.
This guide is for developers and platform engineers who write and review Dockerfiles. It covers the authoring decisions only: base image choice and pinning, multi-stage structure, the build context, package installation, instruction choices such as ADD, ENV and USER, and the build-time attestations Docker can attach. It deliberately does not repeat material NHI Mgmt Group already covers elsewhere. For BuildKit secret and SSH mounts in depth, see How to use build secrets in Docker and BuildKit. For finding and responding to credentials already baked into images, see Secrets in Container Images and Build Artefacts Guide. For the daemon, Compose files and runtime flags, see the Docker and Docker Compose Security Guide. Facts about Docker behaviour come from Docker's own documentation. Recommendations beyond it are labelled as NHI Mgmt Group recommendations.
Key takeaways
- Docker states that build arguments and environment variables are inappropriate for passing secrets because they persist in the final image. Use secret or SSH mounts instead.
- An
ENVvalue set in one layer persists in that layer even if a later layer unsets it. Set, use and unset values in a singleRUN, or better, do not use them for anything sensitive. - Pin base images to a digest for repeatable builds. Docker notes that this trades away automatic security fixes, so pair pins with an automated update process such as Dependabot.
- Use multi-stage builds so the final image contains only what is needed to run the application. Build tools, source and caches stay in earlier stages.
- Keep the build context small with
.dockerignore. Anything sent in the context can be copied into an image by a carelessCOPY . .. - Switch to a non-root
USERwhen the service can run without privileges, and avoidsudoinside images. - Rebuild images regularly with
--pull, because images are immutable snapshots and do not pick up fixes on their own.
Why the Dockerfile is a security boundary
A Dockerfile is a build script that runs with network access, often with credentials for private registries and package feeds, and produces an artefact that will run in production. Each instruction that changes the filesystem creates a layer. Docker describes images as immutable, and layers are kept as they were written. Anything written into a layer stays retrievable from the image even if a later instruction deletes it. That one property explains most Dockerfile security problems. It is why "copy the key, use it, delete it" does not work. It is also why the order and grouping of instructions matter more than they look.
There is also an identity side. Build pipelines hold some of the most powerful non-human credentials in an organisation: registry push tokens, package feed tokens, Git deploy keys and cloud credentials for fetching artefacts. A Dockerfile is where those credentials meet a shareable artefact. Leaking them into an image matches MITRE ATT&CK T1552 Unsecured Credentials. Treat Dockerfile review as part of credential hygiene, not just image hardening.
Choosing a base image
Docker's best practices say the first step towards a secure image is choosing the right base image. They recommend a trusted, small base, because a minimal base minimises the vulnerabilities introduced through dependencies. Docker names its trusted sources on Docker Hub: Docker Official Images, which it describes as curated, documented and regularly updated, plus Verified Publisher and Docker-Sponsored Open Source images, shown by badges on Hub.
Docker also suggests using two bases: a fuller one for building and testing, and a slimmer one for production that has no compilers or build tools. Docker says this can considerably lower the attack surface. Multi-stage builds, covered below, are how you put that into practice in one Dockerfile.
When choosing a base, NHI Mgmt Group recommends asking four questions:
- Who publishes and maintains it, and how quickly do they ship fixes?
- Does the runtime stage need a shell and package manager at all, or can it start from a minimal or empty base?
- Is the base signed, and can your pipeline verify that signature? See How to sign and verify container images with cosign.
- Is it on your organisation's approved base image list? An approved list is far easier to patch than a fleet of individual choices.
Pinning base images without freezing them
A tag such as python:3 or latest is a moving pointer. The same Dockerfile can produce a different image tomorrow, and a compromised or mistaken push upstream reaches you at your next build. Docker's guidance is that, "to fully secure your supply chain integrity", you can pin the image version to a specific digest:
FROM alpine:3.21@sha256:<digest>
(The tag and digest here are illustrative placeholders.) A digest guarantees the same image every build. Docker is clear about the cost: you give up automatic security fixes. A pinned base that nobody updates becomes a known-vulnerable base. Docker points to two ways to keep pins current:
- Docker Scout's "No outdated base images" policy checks whether the base image version you are using is the latest, and flags pinned digests that no longer match their tag.
- Dependabot raises pull requests to update base image tags and digests on a schedule, which Docker notes gives you control and an audit trail.
NHI Mgmt Group recommends keeping both the tag and the digest in the FROM line. The tag tells reviewers what the image is meant to be, and the digest makes it exact. Route digest updates through the same pull request review as code changes, so a base image change is never invisible.
Rebuild on a schedule
Because images are snapshots, Docker recommends rebuilding regularly with updated dependencies. Two flags matter. --pull makes Docker check for and download a newer base image even when a cached copy exists. --no-cache rebuilds every layer and fetches newer package manager dependencies, but does not refresh the base image. Docker notes they can be combined. A scheduled pipeline job running docker build --pull --no-cache catches fixes that have landed since the last release, even when the application code has not changed.
Multi-stage builds: leaving the toolchain behind
Multi-stage builds use more than one FROM instruction. Each starts a new stage, which can use a different base. Docker's documentation explains that you can selectively copy artefacts from one stage to another, leaving behind everything you do not want in the final image. In Docker's example, the final stage starts from scratch, an empty base, and contains nothing but the compiled binary.
An illustrative structure:
FROM golang:<version>@sha256:<digest> AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM scratch
COPY --from=build /out/app /app
USER 10001
ENTRYPOINT ["/app"]
Details from Docker's documentation that affect security:
- Name your stages. Adding
AS <name>letsCOPY --fromrefer to a stage by name, so reordering the file later does not silently copy from the wrong stage. Unnamed stages are referenced by position, starting at 0. COPY --fromcan pull from external images. That includes a local image, a tag or a registry reference. Treat such references like aFROMline: pin them and review them, because they bring files from outside your build.--targetbuilds up to a named stage. Docker gives debug and test stages as typical uses. Keep debug tooling in its own stage and never make it the default target.- BuildKit only builds the stages the target depends on. The legacy builder processes every stage up to the target. With BuildKit, an unrelated stage that fetches something risky will not run unless it is needed.
Multi-stage builds do not make secrets safe. A secret copied into a build stage still sits in that stage's layers in the build cache, and a COPY --from of the wrong directory carries it forward. Secrets still belong in mounts, covered next.
Build secrets: what not to do in a Dockerfile
Docker's secrets documentation is explicit that build arguments and environment variables are inappropriate for passing secrets because they persist in the final image. The supported approach is two steps. Pass the secret to the build client with docker build --secret. Then consume it in a single instruction with RUN --mount=type=secret,id=<id>. By default the secret appears at /run/secrets/<id> inside the build container. The target option changes the path, and the env option exposes the secret as an environment variable for that step instead of a file. For private Git repositories, Docker recommends SSH mounts (docker buildx build --ssh default with RUN --mount=type=ssh). For remote build contexts, BuildKit supports the pre-defined secrets GIT_AUTH_TOKEN and GIT_AUTH_HEADER.
When reviewing a Dockerfile, NHI Mgmt Group suggests flagging any of the following as a blocking finding:
ARGorENVnames that look like credentials, such as anything containing TOKEN, PASSWORD, SECRET or KEYCOPYof files such as.npmrc,.pypirc,.netrc,id_rsa, cloud credential files or.env- credentials embedded in URLs in
RUN,ADDor package manager configuration - a
RUN rmof a credential file in a later instruction than the one that added it
The full mount syntax, CI patterns and migration steps are in How to use build secrets in Docker and BuildKit.
Controlling the build context
The build context is the set of files sent to the builder. Docker recommends a .dockerignore file to exclude files that are not relevant to the build, using patterns that work like .gitignore. From a security view, the context is the pool every COPY and ADD draws from. A broad COPY . . in a repository that contains local .env files, Git history, test fixtures with real data, or a developer's cloud credentials puts all of it in a layer.
NHI Mgmt Group recommends a .dockerignore that excludes at least:
.gitand other version control folders.env,*.pem,*.keyand local credential or configuration files- dependency folders that will be reinstalled, such as
node_modules - build output, logs, and IDE or editor folders
Better still, copy named files and directories (COPY package.json package-lock.json ./, then COPY src/ ./src/) rather than the whole context. That also improves layer caching.
Instruction choices that matter
COPY rather than ADD
Docker's guidance is that you will mostly want COPY, including for copying between stages. ADD is for remote artefacts, and Docker notes it has built-in support for checksum validation of remote resources. NHI Mgmt Group recommends treating ADD with a remote URL as a dependency fetch. If you use it, use its checksum validation, so that a changed file upstream breaks the build instead of shipping.
ENV and ARG persistence
Docker's documentation warns that an environment variable set with ENV persists in its layer even if you unset it in a later layer. Docker's workaround is to set, use and unset the variable in a single RUN. For anything sensitive, the answer is still a secret mount. For non-sensitive configuration, remember that every ENV value is visible to anyone who can inspect the image.
Package installation
Docker advises always combining apt-get update with apt-get install in the same RUN. Run separately, the cached update step can go stale and install outdated packages. NHI Mgmt Group adds three habits:
- Install only what the stage needs, and pin versions where your distribution allows.
- Clean package manager caches in the same
RUNthat created them, so they never land in a layer. - Do package installation in build stages wherever possible, so the runtime stage carries fewer packages to patch.
Fail loudly: pipefail
Without pipefail, a shell pipeline succeeds if only its last command succeeds. Docker recommends prepending set -o pipefail && so that an unexpected error stops the build instead of letting it succeed. This matters for security when a pipeline downloads and verifies something. A failed checksum check upstream of a pipe should never produce a green build.
WORKDIR
Docker says you should always use absolute paths for WORKDIR, and use it instead of chained RUN cd commands. Predictable paths make it easier to reason about what a later COPY overwrites.
Running as a non-root user
Docker's guidance is direct: if a service can run without privileges, use USER to change to a non-root user. A process running as root inside a container has far more ability to do damage if the application is compromised. It also depends entirely on the runtime's isolation to stop that root from mattering on the host.
Docker advises against installing or using sudo because of its unpredictable TTY and signal-forwarding behaviour. If an image needs root for initialisation and then drops to a non-root user, Docker suggests considering gosu. NHI Mgmt Group recommends these practices:
- Create a dedicated user and group in a build or runtime stage, and set
USERbeforeENTRYPOINT. - Use a numeric UID in
USER, so that platforms which enforce non-root can verify it without reading/etc/passwd. - Make application files owned by root and readable by the application user, so a compromised process cannot rewrite its own code.
- Give write access only to the specific directories the application needs.
Runtime settings such as read-only root filesystems, dropped capabilities and rootless daemons sit outside the Dockerfile. They are covered in the Docker and Docker Compose Security Guide.
Entrypoint, signals and ephemeral containers
Docker recommends ENTRYPOINT for the image's main command, with CMD supplying default flags. It says CMD should almost always use the exec form, CMD ["executable", "param1", "param2"]. In exec form the application becomes the container's PID 1 and receives signals directly. Shell form wraps the process in a shell, which can swallow stop signals and leave the platform to kill the container forcibly.
Docker also describes containers as ephemeral: they can be stopped and destroyed, then rebuilt and replaced. It advises that each container has only one concern. For security this means two things. Configuration and state that must survive belong outside the image. And an image that bundles several services gives each of them every other service's packages and permissions.
Attestations: SBOM and provenance at build time
BuildKit can attach two kinds of attestation to an image, in the in-toto JSON format. An SBOM lists the software artefacts an image contains or that were used to build it. Provenance describes how the image was built. Docker's documentation states that provenance attestations at mode=min are added by default, while SBOM attestations are opt-in with --sbom=true. Maximum provenance is opt-in with --provenance=mode=max, and --provenance=false turns provenance off.
Attestations are stored with the image as a manifest in the image index, so they can be inspected in a registry without pulling the whole image. Some constraints are documented. The docker driver needs the containerd image store, the docker-container, kubernetes and remote drivers support attestations, and the local and tar exporters write them as JSON files instead.
NHI Mgmt Group recommends enabling SBOM generation in CI builds and keeping provenance on. Before choosing maximum provenance, review Docker's provenance documentation on what build metadata it records, so you know what it exposes. Attestations answer "what is in this image and how was it made" when a new vulnerability or compromised dependency is announced. They map directly to the provenance expectations in SLSA. See the Container Image Security Guide for how they fit with scanning and signing.
Common failure patterns
- Secrets as build arguments.
--build-arg NPM_TOKEN=...feels temporary but persists in the image, as Docker's documentation warns. - Delete-later secrets. A credential file copied in one instruction and removed in a later one is still in the earlier layer.
- Floating base tags.
FROM node:latestor a major-version tag means unreviewed changes enter every build. - Pinned and forgotten. A digest pin with no Dependabot or Scout policy behind it becomes a known-vulnerable base.
- Single-stage production images. Compilers, package managers and source code ship to production because the build and runtime stages were never split.
COPY . .with no.dockerignore. Git history and local.envfiles end up in layers.- Running as root by default. No
USERinstruction, so the application runs as root for no reason. - Debug stage as the default target. The last stage in the file is the debug stage, so a plain build ships the tools.
- Silent pipeline failures. A
curl | shstyle step withoutpipefailsucceeds even when the download fails.
Practitioner checklist
- Every
FROMand externalCOPY --fromuses an approved base, pinned by tag and digest. - Dependabot or a Docker Scout policy keeps digests current, and updates go through pull request review.
- Production images come from a minimal final stage that contains only runtime artefacts. Stages are named and the production stage is the default target.
- No credentials in
ARG,ENV,COPYor URLs. Secrets come only throughRUN --mount=type=secretor SSH mounts. - A
.dockerignoreexcludes.git,.env, keys and local configuration, andCOPYnames specific paths. apt-get updateandinstallshare aRUN, caches are cleaned in the same step, and pipelines useset -o pipefail.COPYis the default, and any remoteADDuses checksum validation.- A non-root numeric
USERis set, there is nosudo, andENTRYPOINTandCMDuse exec form. - Scheduled rebuilds run with
--pull, and CI builds produce SBOM and provenance attestations.
Standards and references
- Docker Docs: Building best practices
- Docker Docs: Build secrets
- Docker Docs: Multi-stage builds
- Docker Docs: Build attestations
- NIST: SP 800-190 Application Container Security Guide
- NIST: SP 800-218 Secure Software Development Framework (SSDF) Version 1.1
- OpenSSF: SLSA v1.0 Security Levels
- CIS: CIS Controls v8.1
Related NHI Mgmt Group resources: How to use build secrets in Docker and BuildKit · Secrets in Container Images and Build Artefacts Guide · Docker and Docker Compose Security Guide · Container Image Security Guide