
Container Hardening
Practical container security techniques covering image hardening, runtime protection, resource limits, and defensive configurations for Docker and Kubernetes environments.
Introduction
Containers share the host kernel. A compromised container with weak isolation gives an attacker a route to other containers, to data on the host, or to the host itself. Hardening shrinks what is inside the container and tightens the boundaries around it.
This note covers the defensive settings, from building the image to running it. Most of them map directly to an escape in Docker Container Escape Techniques.
Defense in depth
Hardening the container is one layer. It still needs network segmentation, runtime monitoring and image scanning around it.
Image hardening
Use minimal base images
Fewer packages in the image means fewer vulnerable libraries and fewer tools for an attacker who gets a shell.
# Prefer distroless or Alpine images
FROM gcr.io/distroless/static-debian12
# Or
FROM alpine:3.19
# Avoid full OS images like ubuntu:latest or debian:latest
# unless specific packages are requiredSmall base images worth knowing:
gcr.io/distroless/*: Google's distroless images, with no shell or package manageralpine:*: about 5MB, built on musl libcscratch: an empty image for statically compiled binaries
Scan images for vulnerabilities
Scan in the CI/CD pipeline so vulnerable images fail the build instead of reaching production.
# Trivy - Fast vulnerability scanner
trivy image myapp:latest
# Grype - Anchore's scanner
grype myapp:latest
# Docker Scout (built into Docker)
docker scout cve myapp:latestUse multi-stage builds
Build in one stage and copy only the output into the runtime image, so compilers and build tools never ship:
# Build stage
FROM golang:1.22 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp
# Runtime stage - minimal image
FROM gcr.io/distroless/static-debian12
COPY --from=builder /app/myapp /
USER nonroot:nonroot
ENTRYPOINT ["/myapp"]Pin image versions
Don't use latest in production. Pin a version, or better a SHA digest, so the image you tested is the image you run:
# Pin version
FROM nginx:1.25.4-alpine
# Or pin SHA for immutability
FROM nginx@sha256:abc123...Runtime hardening
Run as a non-root user
Create a dedicated user for the application and run as that user, not root:
# In Dockerfile
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser# At runtime
docker run --user 1000:1000 myapp:latest
# Kubernetes
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000Drop capabilities
Docker grants a default set of capabilities to every container. Drop all of them and add back only what the application needs:
# Docker - drop all, add specific
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE myapp
# Kubernetes Pod Security Context
securityContext:
capabilities:
drop:
- ALL
add:
- NET_BIND_SERVICEUse a read-only root filesystem
A read-only root filesystem stops an attacker from dropping tools or changing binaries at runtime:
# Docker
docker run --read-only myapp:latest
# With temp directory for application needs
docker run --read-only --tmpfs /tmp:rw,noexec,nosuid myapp:latest# Kubernetes
securityContext:
readOnlyRootFilesystem: true
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}Limit resources
CPU and memory limits stop one container from starving the host:
# Docker
docker run --memory=512m --cpus=0.5 myapp:latest# Kubernetes
resources:
limits:
memory: "512Mi"
cpu: "500m"
requests:
memory: "256Mi"
cpu: "250m"Disable privilege escalation
no-new-privileges stops processes from gaining privileges through setuid binaries:
# Kubernetes
securityContext:
allowPrivilegeEscalation: false# Docker
docker run --security-opt=no-new-privileges myapp:latestNetwork security
Use network policies
In Kubernetes, network policies restrict which pods can talk to each other:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
spec:
podSelector: {}
policyTypes:
- Ingress
ingress: []
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-specific
spec:
podSelector:
matchLabels:
app: backend
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- port: 8080Isolate container networks
# Create isolated network
docker network create --driver bridge --internal isolated-net
# Run container on isolated network
docker run --network isolated-net myapp:latestSecret management
Keep secrets out of images
A secret added in any layer stays in the image history, even if a later layer deletes it:
# BAD - Secret in image
ENV API_KEY=secret123
# GOOD - Use runtime secrets
# Pass at runtime via environment or secret managementUse a secret manager
# Docker Secrets (Swarm)
echo "mysecret" | docker secret create db_password -
docker service create --secret db_password myapp
# Kubernetes Secrets
kubectl create secret generic db-creds \
--from-literal=password=mysecret# Mount as volume (preferred over env vars)
volumes:
- name: secret-volume
secret:
secretName: db-creds
volumeMounts:
- name: secret-volume
mountPath: /secrets
readOnly: trueMonitoring and detection
Enable container logging
Ship container logs to a central store so they survive the container:
# Docker logging drivers
docker run --log-driver=json-file \
--log-opt max-size=10m \
--log-opt max-file=3 \
myapp:latestRuntime security monitoring
Runtime tools watch what containers do and alert on behavior such as a shell spawning or a sensitive file being read:
| Tool | Approach |
|---|---|
| Falco | Syscall monitoring with rules |
| Sysdig | Container visibility and forensics |
| Aqua Security | Commercial runtime protection |
| Tetragon | eBPF-based observability and enforcement |
# Example Falco rule for detecting shell spawns
- rule: Shell Spawned in Container
desc: Detect shell execution in container
condition: >
spawned_process and container and
proc.name in (bash, sh, zsh, ksh)
output: >
Shell spawned in container
(user=%user.name container=%container.name shell=%proc.name)
priority: WARNINGKubernetes-specific hardening
Pod Security Standards
Enforce security baselines with Pod Security Admission:
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restrictedService account hardening
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp
automountServiceAccountToken: false
---
apiVersion: v1
kind: Pod
spec:
serviceAccountName: myapp
automountServiceAccountToken: falseHardened container example
# Kubernetes Pod with hardening best practices
apiVersion: v1
kind: Pod
metadata:
name: hardened-app
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:1.0.0@sha256:abc123
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
resources:
limits:
memory: "512Mi"
cpu: "500m"
requests:
memory: "256Mi"
cpu: "250m"
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
automountServiceAccountToken: falseRelated resources
- Docker Container Escape Techniques: the attacks these settings prevent
- Cloud Security: cloud-native security practices
References
MITRE ATT&CK techniques (defensive context)
- T1610 - Deploy Container - Malicious container deployment
- T1611 - Escape to Host - Container escape techniques
- T1613 - Container and Resource Discovery - Container enumeration
- T1525 - Implant Internal Image - Supply chain attacks
CWE entries
- CWE-250 - Execution with Unnecessary Privileges - Running as root
- CWE-269 - Improper Privilege Management - Capability management
- CWE-522 - Insufficiently Protected Credentials - Secret management
Official documentation
Containerization Fundamentals
Security-focused overview of Docker and Kubernetes architecture, covering isolation mechanisms, security boundaries, and common misconfigurations from an offensive security perspective.
Defense Evasion
Notes on getting past EDR, antivirus, AMSI and application control during red team operations and penetration tests.