Container image hygiene: slim bases, digests and scanning
Pin base images by digest and let a bot move the pin. Why that beats floating tags and manual bumps, with a multi-stage Dockerfile and a CI scan.
Pin every base image by digest, and let a bot propose the new digest each week. That is the whole position. A floating tag such as node:22 gives you freshness you did not choose and builds you cannot reproduce. A manual pin gives you reproducibility that decays the day the person who pinned it forgets. A digest pin plus an update bot gives you both: the bytes in production are exactly the bytes you tested, and the bytes change only through a pull request that CI has already built and scanned.
A container image is a small operating system you ship alongside a few megabytes of your own code: a distribution, a package manager, a shell, certificate bundles, libraries nobody on the team chose. Each has its own release cadence and its own vulnerability list. The routine below is meant to be small enough that a team with no security engineer will actually keep running it. The Dockerfiles assume Node.js, but the reasoning is not specific to Node. It relates to configuration and secrets in multi-service Node apps, since an image should never contain secrets.
A tag is a label, not a version#
A tag is movable. Docker's build best practices say image tags are mutable, so a publisher can point a tag at a new image, and that pinning the digest guarantees the same image even if the tag is replaced, at the cost of updating it yourself. The syntax is image:tag@sha256:...: the tag documents intent and the digest fixes the bytes.
To get the digest of the image you use today:
docker buildx imagetools inspect node:22-bookworm-slimThe output has a top-level Digest: line for the index, plus per-platform entries. Take the top-level index digest so the same line resolves on both amd64 and arm64 builders; a digest pinned for one platform will not resolve on another (see the imagetools inspect reference). The value is 64 hexadecimal characters. In the Dockerfile below, the sha256:0123...cdef string is a stand-in of that shape, not a real image: replace it with the digest your command prints.
The Dockerfile that follows from the position#
# sha256 value below is a placeholder: replace it with the digest from imagetools inspect.
FROM node:22-bookworm-slim@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM deps AS build
COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev
FROM node:22-bookworm-slim@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
CMD ["node", "dist/server.js"]The digest is written inline in each FROM, not in an ARG, so that the bot in the last section can find and rewrite it. What the rest does:
- Stages separate build from runtime. Only the artifacts needed at runtime reach the final stage; compilers, dev dependencies and source stay behind.
npm cibefore copying the source keeps the dependency layer cached until the lockfile changes, andnpm prune --omit=devstrips development dependencies from the copiednode_modules.COPY --chownsets ownership at copy time. Without it, copied files are owned by UID and GID 0.USER node. The official Node images create an unprivilegednodeuser (UID 1000) and set up its home directory, so you can switch to it without adding anything. Run as non-root because a compromised process then lacks privileges inside the container.CMDin exec form makes the Node process PID 1, so it receives SIGTERM directly, which matters for graceful shutdown on Cloud Run.
Add a .dockerignore listing .git, node_modules, dist, .env* and coverage. The .env* line is the important one: an env file copied into a layer stays in the image history even if a later step deletes it, and the same is true of any secret copied and removed in a later instruction.
If the runtime needs an OS package, install it in one layer with the index update, without recommended packages, and clear the lists in the same layer:
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*Running apt-get update in its own layer lets the build cache serve a stale package index to a later install.
The objection: pins hide good news#
The strongest argument against digest pinning is that it can make you less safe. A pinned base does not receive a patch until the digest changes. If the bot is turned off, or its pull requests pile up unmerged, you run an old base with total confidence, and a floating tag would have patched itself on the next build.
That is true, and it is why the pin is half the position and the bot is the other half. A floating tag does patch itself, but it also changes on a Tuesday for reasons unrelated to your commit, which makes a regression hard to bisect. A pin turns that change into a reviewable diff with a green or red CI run attached. The cost is that you must keep the update path alive, so treat the age of the deployed digest as something to watch, and alert on it if you can.
Dependabot is the usual bot. Its docker ecosystem updates FROM lines that carry a tag and digest:
version: 2
updates:
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"Each week you get a pull request changing the digest. CI builds the image, runs the scan and your tests, and you merge if green. Two caveats from GitHub's documentation on supported ecosystems: Docker is not supported for Dependabot security updates, so do not rely on it to flag a vulnerable base. The registry scan below is for that. And the version updates cover files it can parse, so a digest hidden behind an ARG is not updated.
Separately, rebuild on a schedule. Docker's guide recommends rebuilding regularly with updated dependencies, and notes that --pull forces a check for a newer base while --no-cache alone does not pull a fresh one. With a pinned base the digest update is what brings the new base, so the scheduled rebuild matters most for packages you install on top and for application dependencies.
Scan for what you can fix#
Scanning has two jobs: stop a known-bad image from shipping, and tell you when a new vulnerability is published against an image already running. They want different settings.
For the build gate I use Trivy. trivy image takes the image name and the documented flags include --severity, --exit-code and --ignore-unfixed (show only vulnerabilities that have a fix); see the CLI reference.
docker build -t myapp:ci .
trivy image \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--exit-code 1 \
myapp:ci--ignore-unfixed keeps the gate honest. A finding with no available fix cannot be resolved by the person reading the failure, so failing the build on it teaches people to bypass the check. Track those in the registry scan, where they cost nothing. Findings in intermediate build stages do not matter, because only the final stage ships; scan the final image only. Different scanners also disagree on the same image because their advisory databases and matching rules differ, so pick one gate, tune it once, and treat any other as a second opinion.
For continuous scanning on Google Cloud, Artifact Analysis scans images pushed to Artifact Registry. Per Google's documentation, scanning is off by default for Artifact Registry repositories until you enable it, and vulnerability information for automatically scanned images is kept up to date as new vulnerabilities are found. On-demand scanning is a manual command whose results last up to 48 hours. See Artifact Analysis. To read results:
gcloud artifacts docker images list --show-occurrences \
--occurrence-filter='kind="VULNERABILITY"' --format=json \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_IDIt returns the 10 most recent results by default, and takes the image path without a tag or digest suffix.
Artifact Analysis scanning is billed on top of storage; see Artifact Analysis pricing for current rates. Two ways to keep the bill down: scan only repositories that hold deployable images, and do not push every pull request build into the same repository as release images, deleting stale tags with a cleanup policy. A scanner in CI costs only build minutes and is a good first step before paying for registry scanning.
Where the position stops holding#
Choosing the base itself. Digest pinning is orthogonal to which base you pin. The default node:22 is full Debian with build packages, the largest surface. The -slim variant omits most of those packages. Alpine uses musl libc instead of glibc (see the Docker Node.js image documentation), which can make prebuilt native modules misbehave, so I do not default to it unless dependencies are pure JavaScript. Distroless, gcr.io/distroless/nodejs22-debian13, ships only the runtime and its dependencies, with no shell or package manager.
If you move the final stage to distroless, pin it the same way, with the nonroot tag, and keep the pin where the bot can see it:
# sha256 value below is a placeholder: replace it with the digest from imagetools inspect.
FROM gcr.io/distroless/nodejs22-debian13:nonroot@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef AS runtime
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
CMD ["dist/server.js"]The distroless Node images supply the node binary, so CMD carries only the script path, and it must be in exec form because there is no shell. The cost is debugging: nothing to open in production. Plan for structured logs (see structured logging on a budget), keep a build of the same image from the debug-nonroot tag, which adds a busybox shell (docker run --entrypoint=sh -ti <image>), and never ship it. Files copied from the build stage are root-owned and world-readable, which suffices for a service that does not write to disk; if yours does, give it an explicit writable directory with the right ownership, because running as non-root otherwise fails with a permissions error at the first write. If the team cannot debug without a shell, a slim non-root image captures most of the benefit with less friction.
Platforms that build for you. With a buildpack or a platform that builds and patches images on your behalf, much of this is done for you and the effort goes into application dependencies.
Short-lived prototypes. A service that will not outlive the month does not justify digest bots and scan gates. Run non-root, keep secrets out of the image, and stop there.
Teams that will not merge the bot's pull requests. Then the pin is a liability, and a floating tag with a scheduled rebuild and a registry scan is the more honest setup. The position depends on someone merging a small pull request each week.
Related articles
All articles →How a small team can keep Terraform state safe: a versioned GCS backend, locking you can trust, and a state layout that limits the damage of a bad apply.
10 min
Why a scheduled job can fail for weeks without anyone noticing, and the retry, idempotency and alerting setup that makes Cloud Scheduler failures loud.
13 min
How to choose between git submodules and a pnpm workspace when several services share code, plus the Docker build that ships one app from a workspace.
10 min