What are the best practices for container image and runtime security?
Build time
- Minimal, maintained base images (distroless, Alpine, Chainguard, UBI-micro), pinned by version or digest and rebuilt regularly to pick up patches.
- Multi-stage builds so compilers, package managers and sources never reach the runtime image.
- Scan images in CI (Trivy, Grype, Docker Scout) and in the registry continuously; fail on fixable critical vulnerabilities.
- No secrets in images: they persist in layers and history even if deleted later. Use BuildKit secret mounts (
RUN --mount=type=secret,id=npmrc ...) for build-time credentials. - Generate an SBOM and sign images (cosign); verify signatures at deploy time.
- Lint Dockerfiles (hadolint).
Runtime
- Run as non-root (
USER app,runAsNonRoot: true), with a read-only root filesystem and explicit writableemptyDirvolumes for temp files. - Drop all Linux capabilities and add back only what is needed;
allowPrivilegeEscalation: false; seccompRuntimeDefaultprofile. - Never run privileged containers or mount the Docker socket into application containers.
- Resource limits to contain denial of service; network policies to limit lateral movement.
- Rootless Docker or Podman on build hosts; runtime threat detection (Falco).
Example
yaml
securityContext: # Kubernetes container security context
runAsNonRoot: true
runAsUser: 10001
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
seccompProfile: { type: RuntimeDefault }Follow-up questions interviewers ask
Try answering each one before you open it.
Why is mounting /var/run/docker.sock into a container dangerous?
Whoever can talk to the Docker socket can start a privileged container that mounts the host's root filesystem, which is equivalent to root on the host. CI systems that need to build images should use daemonless builders (Kaniko, BuildKit rootless, Jib, Buildah) instead.