Containers have changed how software is packaged and deployed. A development team can build an application into an image, store it in a registry, and run that image consistently across development, testing, and production environments.
This consistency is valuable, but it does not automatically make containers secure.
A container image can contain vulnerable operating-system packages, outdated application dependencies, exposed credentials, unnecessary utilities, insecure configuration, or software from an untrusted source. If an image is compromised before deployment, the problem can travel through the entire delivery pipeline.
Container security therefore needs to cover more than the running container. It begins with the source code and build process, continues through image storage and distribution, and extends into runtime monitoring.
A useful way to approach the problem is to treat the image as a software supply-chain artifact. Every stage should establish where the image came from, what it contains, whether it has been inspected, and whether it is allowed to run.
This article examines practical controls from the first Dockerfile instruction through registry publication and runtime deployment.
1. Understand the Container Image Attack Surface
A container image is made from layers. Those layers may contain:
- A base operating-system filesystem
- System libraries and packages
- Application runtime dependencies
- Application code
- Build outputs
- Configuration files
- Supporting tools
The final image is not necessarily limited to the files the application needs at runtime. Poorly designed build processes may leave behind compilers, package managers, temporary files, test utilities, source code, or credentials.
Consider a basic Dockerfile:
FROM node:22
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]
This may work, but it leaves important questions unanswered:
- Is the base image trusted and maintained?
- Are dependency versions reproducible?
- Does the image contain development dependencies?
- Is the application running as root?
- Could local files or secrets enter the build context?
- Has the resulting image been scanned?
- Can the registry prove who published it?
These are security design questions, not merely Docker syntax questions.
A secure image pipeline reduces unnecessary components, protects sensitive build inputs, verifies dependencies, and establishes controls around publishing and deployment.
2. Choose Base Images Carefully
The base image is the foundation of the container. It influences the operating-system packages, libraries, default users, and tools that become part of the final image.
A familiar base image is not automatically a secure base image.
Use trusted sources
Prefer official images or images published by vendors and organizations with a clear maintenance process.
Before adopting an image, evaluate:
- Publisher identity
- Supported versions
- Update frequency
- Vulnerability response process
- Available architecture variants
- Included operating-system packages
- Image provenance and signing support
Avoid choosing an image only because it is popular or small.
Alpine images
Alpine Linux images are commonly used because they are relatively small.
They can reduce image size, but teams should verify compatibility with native libraries, runtime dependencies, and application packages.
A smaller image is not necessarily a more secure image if the team cannot maintain it or if it introduces compatibility workarounds.
Distroless images
Distroless images aim to include an application and its runtime dependencies without a conventional package manager or general-purpose shell.
This reduces the number of tools available inside the runtime image. It can also make debugging less familiar, so teams need external logging, metrics, tracing, and appropriate debugging procedures.
Pin image versions
Avoid relying on an unqualified moving tag such as:
FROM node:latest
A future build may resolve to a different image without an intentional application change.
Use an explicit supported version:
FROM node:22-bookworm-slim
For stronger reproducibility, pin the image by digest:
FROM node:22-bookworm-slim@sha256:REPLACE_WITH_VERIFIED_DIGEST
The digest must be obtained from the trusted registry and updated through a controlled process.
Pinning does not mean never updating. It means image changes are deliberate, reviewable, and testable.
3. Build-Time Security: Keep the Final Image Clean
A good build pipeline separates the environment used to compile software from the environment used to run it.
Docker multi-stage builds make this possible.
Example: Multi-stage Node.js Dockerfile
# Build stage
FROM node:22-bookworm-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:22-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev \
&& npm cache clean --force
COPY --from=builder /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
This example assumes the application produces a dist directory and that the runtime only requires production dependencies. Adapt it to the actual framework and build output.
The builder contains the tooling needed to compile the application. The runtime receives only the files required to execute it.
Use a .dockerignore file
The Docker build context can accidentally include files that should never enter an image.
Create a .dockerignore file:
node_modules
.git
.env
.env.*
*.pem
*.key
*.log
coverage
dist
.DS_Store
The exact exclusions depend on the application. The purpose is to prevent unnecessary files and sensitive local material from being sent into the build context.
Never bake secrets into image layers
A common mistake is passing credentials through Docker build arguments:
ARG PRIVATE_TOKEN
RUN npm config set //registry.example.com/:_authToken=$PRIVATE_TOKEN
Build arguments and environment variables are not appropriate secret-storage mechanisms because values may persist in image metadata, layers, or build records.
Docker provides build secret mounts for this purpose. Example:
# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" \
npm ci
COPY . .
RUN npm run build
Build with:
docker build \
--secret id=npm_token,src="$HOME/.npm-token" \
-t example-app:1.0.0 .
The secret is mounted for the relevant build instruction rather than intentionally copied into the resulting image.
4. Vulnerability Scanning: Inspect What You Ship
A container image may include vulnerable operating-system packages or application dependencies.
Vulnerability scanning helps identify known issues before an image reaches production.
It is not a guarantee that an image is safe. Scanners depend on available vulnerability intelligence, package identification, and the configuration used during scanning.
Trivy
Trivy can scan container images for vulnerabilities and other security issues.
Example:
trivy image example-app:1.0.0
To focus on higher-severity vulnerabilities:
trivy image \
--severity HIGH,CRITICAL \
example-app:1.0.0
To make the command fail when findings meet the configured severity:
trivy image \
--severity HIGH,CRITICAL \
--exit-code 1 \
example-app:1.0.0
The exit code matters in automation. A pipeline that merely prints findings but always exits successfully may allow a vulnerable image to proceed without anyone noticing.
Integrate scanning into CI
Example GitHub Actions workflow:
name: Container Security
on:
pull_request:
push:
branches:
- main
jobs:
build-and-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build image
run: |
docker build -t example-app:${{ github.sha }} .
- name: Scan image
uses: aquasecurity/trivy-action@0.28.0
with:
image-ref: example-app:${{ github.sha }}
severity: HIGH,CRITICAL
exit-code: '1'
This illustrates the integration pattern. In a production pipeline, review and pin third-party actions to verified immutable commit SHAs.
Handle findings intelligently
Not every scanner finding has the same operational impact.
A team should evaluate:
- Severity
- Whether the vulnerable component is actually present
- Whether the affected code path is reachable
- Whether an exploit is known
- Whether a patched version exists
- Whether an upgrade introduces compatibility risk
- Whether a temporary mitigation is available
Document accepted risks with an owner and review date. Do not silently ignore recurring critical findings.
5. Registry Security: Protect the Distribution Point
A container registry stores and distributes images. It may be public or private and may be operated by a cloud provider, Git hosting platform, or private infrastructure.
A compromised registry account can be as damaging as a compromised build environment.
Control registry access
Use separate identities for developers, CI systems, and production deployment systems.
Apply least privilege:
- Developers should receive only the access needed for their work
- CI should publish only to the intended repositories
- Production systems should pull approved images
- Administrative privileges should be restricted and monitored
Use short-lived credentials or supported workload identity mechanisms where possible.
Use immutable release identifiers
Avoid using latest as the only production reference.
A deployment using:
example-app:latest
does not clearly identify the exact artifact that was tested.
Prefer versioned tags:
example-app:1.4.2
For stronger artifact identity, deploy by digest:
example-app@sha256:IMAGE_DIGEST
A digest identifies a specific image manifest. It helps ensure that the image deployed is the same artifact that passed testing.
Sign images and verify them
Image signing provides a way to verify that an artifact was signed by an expected identity.
Tools such as Cosign can be incorporated into a signing and verification process.
A simplified workflow is:
cosign sign --key cosign.key \
registry.example.com/team/app@sha256:IMAGE_DIGEST
Verification:
cosign verify \
--key cosign.pub \
registry.example.com/team/app@sha256:IMAGE_DIGEST
This is an illustrative key-based workflow. Production signing should include secure key storage, rotation, identity controls, and a documented verification policy.
Signing does not prove that the application is free of vulnerabilities. It helps establish artifact integrity and signer identity.
6. Runtime Security: Restrict What the Container Can Do
A secure image can still be deployed insecurely.
Runtime configuration determines the privileges, filesystem access, network exposure, and resource consumption available to the process.
Run as a non-root user
If an application does not need root privileges, do not run it as root.
A Dockerfile can specify:
USER 10001:10001
The selected UID and GID must have permission to access the application files and required directories.
Use a read-only filesystem
Where the application supports it, mount the container root filesystem as read-only.
Example:
docker run \
--read-only \
--tmpfs /tmp \
--cap-drop ALL \
--security-opt no-new-privileges \
example-app:1.0.0
This example removes Linux capabilities and prevents privilege escalation through certain execution paths.
Set resource limits
Containers should not be allowed to consume unlimited host resources.
Example:
docker run \
--memory=512m \
--cpus=1.0 \
--pids-limit=100 \
example-app:1.0.0
Resource limits reduce the ability of a malfunctioning or compromised container to exhaust host resources.
Avoid unnecessary network exposure
Expose only the ports the application needs.
Do not publish database ports to the public internet merely because another container needs database access. Use internal container networks and firewall rules.
7. Software Supply-Chain Security: Know What You Deploy
Scanning images is one part of supply-chain security. Teams also need visibility into the components and processes that produced an artifact.
Software Bill of Materials
A Software Bill of Materials (SBOM) records components included in a software artifact.
It can help teams identify whether a newly disclosed vulnerability affects a library or package inside an image.
Example with Trivy:
trivy image \
--format cyclonedx \
--output sbom.json \
example-app:1.0.0
Store the SBOM with the build records or publish it through an appropriate artifact-management process.
Build provenance
Provenance records information about how an artifact was produced, including the source revision, build process, and builder identity.
It helps answer questions such as:
- Which source commit produced this image?
- Which pipeline built it?
- Which dependencies were used?
- Was the build process approved?
- Is the deployed image the artifact produced by the trusted pipeline?
Establish a release policy
A practical container release policy might require:
- Build from reviewed source
- Use an approved base image
- Run automated tests
- Generate an SBOM
- Scan for vulnerabilities and secrets
- Sign the image
- Publish to an approved registry
- Verify the image before deployment
- Record the deployed digest
- Monitor and rebuild when relevant vulnerabilities are discovered
This creates a traceable chain from source code to production.
8. A Practical Container Security Pipeline
A small engineering team does not need to introduce every enterprise security platform on day one.
It can begin with a manageable set of controls:
Source Code
|
v
Code Review
|
v
Automated Tests
|
v
Docker Build
|
v
Secret and Vulnerability Scan
|
v
SBOM Generation
|
v
Image Signing
|
v
Private Registry
|
v
Image Verification
|
v
Production Deployment
|
v
Runtime Monitoring
Each stage should produce evidence that the next stage can trust.
For example, the deployment pipeline should not simply pull the newest image tag. It should deploy a known image digest that has passed the required checks.
Key Takeaways
- Container security begins during image creation and continues through registry storage and runtime operation
- Use trusted, maintained base images and update them through a controlled process
- Multi-stage builds reduce unnecessary files and dependencies in the runtime image
- Never bake credentials into image layers; use secure build-secret mechanisms
- Scan, sign, track, and verify images before allowing them into production
Conclusion: Containers provide a consistent way to package and distribute applications, but consistency is not the same as security. A container image should be treated as a release artifact with a known origin, controlled contents, and a verifiable deployment path. Teams that protect the build process, inspect dependencies, secure registries, and restrict runtime privileges reduce the opportunities for vulnerabilities to travel from development into production. The objective is not to create an image that can never contain a vulnerability. The objective is to make the image easier to inspect, harder to tamper with, safer to run, and faster to replace when a problem is discovered.
Published by the DSSS Engineering Team. For corrections or topic requests, use the contact page.