DevSecOps chapter
Ebook draft

AirborneOps Learning Labs · Container security

Container Runtime Hardening

Runtime hardening limits what a deployed container can do if its application is misused or compromised. This chapter turns least privilege into inspectable Docker and Kubernetes settings, then shows how to verify the effective workload.

Ebook draft: These recommendations and examples are starting guidance, not a security guarantee. Adapt them to your application, threat model, runtime and orchestrator version, and operational requirements. All sample configuration, names, paths, image references, and resource values below are illustrative rather than production-ready.

01 · Least privilege

Use a non-root identity and remove unneeded privileges

Set the application process to a dedicated, non-root numeric UID and GID, and make image files readable by that identity. Avoid adding capabilities by habit. Begin by dropping all Linux capabilities, then add back only a narrowly justified capability if a tested requirement remains. Most HTTP services can bind to a port above 1023 and need no extra capability. Disable privilege escalation so a process cannot gain privileges through mechanisms such as set-user-ID programs. Docker documents a restricted default capability set; dropping more is a workload decision, so check startup, health, and normal traffic after each change. See Docker Engine security and the Kubernetes application security checklist. The field meanings and constraints are detailed in the Kubernetes security context documentation.

Docker Engine · illustrative run command with a non-root user and no added capabilities
# Illustrative Linux sample. Replace the image, paths, ports, and limits for your service.
docker run --detach --name runtime-api \
  --user 10001:10001 \
  --cap-drop ALL \
  --security-opt no-new-privileges:true \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --mount type=bind,src=/srv/runtime-api-config,dst=/etc/runtime-api,readonly \
  --memory=512m --cpus=1.0 --pids-limit=128 \
  --network app-net \
  --publish 127.0.0.1:8080:8080 \
  registry.example.com/team/runtime-api@sha256:<reviewed-image-digest>
Kubernetes · illustrative workload security context and writable paths
# Illustrative Linux Deployment. Labels, image digest, and sizing are sample values.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: runtime-api
  namespace: apps
spec:
  replicas: 2
  selector:
    matchLabels:
      app: runtime-api
  template:
    metadata:
      labels:
        app: runtime-api
    spec:
      hostNetwork: false
      hostPID: false
      hostIPC: false
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          image: registry.example.com/team/runtime-api@sha256:<reviewed-image-digest>
          ports:
            - name: http
              containerPort: 8080
          securityContext:
            privileged: false
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
              ephemeral-storage: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi
              ephemeral-storage: 512Mi
          volumeMounts:
            - name: scratch
              mountPath: /tmp
            - name: app-config
              mountPath: /etc/runtime-api
              readOnly: true
      volumes:
        - name: scratch
          emptyDir:
            medium: Memory
            sizeLimit: 64Mi
        - name: app-config
          configMap:
            name: runtime-api-config
            defaultMode: 0444

The Kubernetes sample sets the identity at Pod scope and privilege controls on the container. Kubernetes treats allowPrivilegeEscalation as true when it is omitted; explicitly set it to false. A privileged container or one granted CAP_SYS_ADMIN cannot use that restriction as intended. Keep both out of an ordinary application workload. The pod and container security-context fields in this example target Linux containers; many do not have equivalent behavior on Windows.

02 · Writable surface and host boundary

Make the root filesystem read-only and mount only what the app needs

A read-only root filesystem turns unexpected writes into visible failures. Identify actual writable paths first, then expose only those paths through small, bounded temporary volumes or persistent storage with the narrowest access mode. Keep config and secret mounts read-only. Set ownership and permissions for the chosen UID rather than running as root to make writes succeed. In Docker, --read-only leaves explicit mounts writable; in Kubernetes, readOnlyRootFilesystem works with declared volumes such as the bounded emptyDir for /tmp above. A memory-backed emptyDir consumes Pod memory, so include it in sizing.

Keep host integration out of application containers. Do not mount the Docker or container-runtime socket, host filesystems, sensitive host paths, or devices; do not use privileged mode or host PID, IPC, or network namespaces for routine workloads. Read-only host mounts still expose host data. If an agent or infrastructure component truly needs a host interface, isolate it as a separately reviewed, narrowly scoped workload.

In Docker, inspect --mount sources and targets before launch. In Kubernetes, review each volumes and volumeMounts entry, reject hostPath for application Pods, and keep host namespace and device fields unset or false. Docker warns that access to its daemon socket can provide the ability to create or manipulate host containers; treat that socket as host-level authority.

03 · Network and platform limits

Allow required connections, cap resource use, and keep syscall filters enabled

Publish only the ports that must be reachable. Docker's -p publishes on every host interface when no bind address is supplied; use an explicit address when a local proxy is the intended entry point. A user-defined Docker network separates network membership, but does not by itself constrain outbound destinations. For a service with no external egress requirement, create an internal bridge with docker network create --internal and connect only required peers. Containers on that bridge can reach each other on all ports, so it segments network membership rather than enforcing a per-service port policy. For outbound access to external services, use host firewall or network controls that allow only the required destination and port, then test one allowed and one denied path. Or use --network none when the workload needs no network.

For Kubernetes, use NetworkPolicy to allow only expected ingress and egress peers and ports. Policies are additive and a connection needs permission at both ends where policies isolate both Pods. A policy has no effect unless the cluster's network plugin implements it. Default-deny egress also blocks DNS; allow the cluster's actual DNS service when needed. Core NetworkPolicy does not select external services by DNS name, so use a suitable egress gateway or CNI-specific feature for external destinations and verify that platform's semantics. The official Docker bridge networking guide and Kubernetes NetworkPolicy documentation describe these platform boundaries.

Kubernetes networking.k8s.io/v1 · sample allow-list; labels are cluster-specific
# Illustrative allow-list for a selected app. Verify the namespace and Pod labels first.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: runtime-api-allow-list
  namespace: apps
spec:
  podSelector:
    matchLabels:
      app: runtime-api
  policyTypes: [Ingress, Egress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ingress-system
          podSelector:
            matchLabels:
              app.kubernetes.io/name: edge-controller
      ports:
        - protocol: TCP
          port: 8080
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: data
          podSelector:
            matchLabels:
              app: orders-db
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

Set CPU and memory requests and limits from measured service behavior, then test overload and graceful failure in a controlled environment. Docker exposes options such as --memory, --cpus, and --pids-limit; the current Docker reference marks --cpus as API 1.25 or newer. Kubernetes declares CPU, memory, and ephemeral-storage requests and limits in the Pod spec. Core Kubernetes does not provide a per-Pod PID limit field in a Deployment; PID ceilings are commonly set in node or runtime configuration, so confirm your platform's setting. A CPU limit can throttle work and a memory limit can cause an OOM kill; values that are too low can become an availability problem.

Keep the Docker default seccomp profile enabled unless testing demonstrates a need for a custom, narrower profile. Never use seccomp=unconfined as a compatibility shortcut. Kubernetes can request RuntimeDefault or a node-installed Localhost profile; custom profiles must exist on every node where a Pod can run. Kubernetes seccomp fields have been stable since v1.19, but runtime defaults can differ. AppArmor or SELinux may add another layer when the host and runtime support them. See the official Docker seccomp profile guidance and Kubernetes seccomp guidance. Do not claim that a profile is active based only on a source YAML file. On Docker, the default profile is applied unless it is explicitly disabled or replaced. A reviewed custom profile can be selected with --security-opt seccomp=/etc/docker/seccomp/runtime-api.json; that path is on the Docker Engine host, and the complete custom profile must be present on each host. Test it as a complete policy rather than assuming it layers on top of the default.

These examples use the current Docker CLI and Kubernetes manifest field shapes. Check the installed Engine API, Linux kernel, orchestrator, container runtime, CNI, and admission-policy versions before adopting syntax or expected behavior. Pod Security Admission became generally available in Kubernetes v1.25; if you enforce Pod Security Standards, pin policy labels to a Kubernetes version supported by your cluster and review workload compatibility first.

04 · Effective-state checks

Verify the running container or Pod, not just its manifest

Inspect a specific running instance after admission and startup. Use authorized diagnostic access, and run write, network, or load probes in a safe test environment when they could affect service. Minimal and distroless images may not include a shell,grep, or nc; do not add tools to production just for a check. Use trusted node/runtime telemetry or a controlled diagnostic container with equivalent policy when in-container commands are unavailable.

Docker · inspect effective configuration and the process status
docker inspect --format 'user={{.Config.User}} privileged={{.HostConfig.Privileged}} pidMode={{.HostConfig.PidMode}} ipcMode={{.HostConfig.IpcMode}} network={{.HostConfig.NetworkMode}} readOnlyRoot={{.HostConfig.ReadonlyRootfs}} capDrop={{json .HostConfig.CapDrop}} security={{json .HostConfig.SecurityOpt}} devices={{json .HostConfig.Devices}} memory={{.HostConfig.Memory}} nanoCpus={{.HostConfig.NanoCpus}} pids={{.HostConfig.PidsLimit}} mounts={{json .Mounts}}' "$CID"
docker exec "$CID" id
docker exec "$CID" sh -c 'grep -E "^(CapEff|NoNewPrivs):" /proc/1/status'
Kubernetes · inspect the admitted Pod and its running process
kubectl get pod "$POD" -n apps -o yaml
kubectl exec -n apps "$POD" -c app -- id
kubectl exec -n apps "$POD" -c app -- sh -c 'grep -E "^(CapEff|NoNewPrivs):" /proc/1/status'
kubectl get pod "$POD" -n apps -o jsonpath='{.spec.hostNetwork}{" "}{.spec.hostPID}{" "}{.spec.hostIPC}{"
"}{.spec.volumes[*].hostPath.path}{"
"}'
Filesystem probes · run in a safe test workload; failed root write is expected
# In the test image, make this directory writable by the application UID before enabling read-only root.
# Expected: this write then fails on the read-only root; the declared temporary path is writable.
docker exec "$CID" sh -c 'touch /var/lib/runtime-api/rootfs-write-probe'
docker exec "$CID" sh -c 'touch /tmp/write-probe && rm /tmp/write-probe'

kubectl exec -n apps "$POD" -c app -- sh -c 'touch /var/lib/runtime-api/rootfs-write-probe'
kubectl exec -n apps "$POD" -c app -- sh -c 'touch /tmp/write-probe && rm /tmp/write-probe'
Network probes · run from the workload and approved and unapproved source Pods
# Replace sample names and ports with one allowed and one denied path.
# Docker: create this no-external-egress variant, then use --network app-private at launch.
docker network create --driver bridge --internal app-private
docker network inspect app-private
docker exec "$CID" nc -vz orders-db 5432
docker exec "$CID" nc -vz 203.0.113.10 443

# When Docker needs outbound internet access, set these to controlled allow/deny test endpoints;
# enforce the rule with the host firewall or network control, not bridge membership alone.
docker exec "$CID" nc -vz "$ALLOWED_EGRESS_HOST" "$ALLOWED_EGRESS_PORT"
docker exec "$CID" nc -vz "$DENIED_EGRESS_HOST" "$DENIED_EGRESS_PORT"

# Kubernetes: a selected NetworkPolicy should allow the database peer and deny the other peer.
kubectl exec -n apps "$POD" -c app -- nc -vz orders-db.data.svc.cluster.local 5432
kubectl exec -n apps "$POD" -c app -- nc -vz unrelated-service.data.svc.cluster.local 5432

# Test ingress separately from an approved source Pod and an unapproved source Pod.
kubectl exec -n ingress-system "$APPROVED_SOURCE_POD" -- nc -vz runtime-api.apps.svc.cluster.local 8080
kubectl exec -n apps "$UNAPPROVED_SOURCE_POD" -- nc -vz runtime-api.apps.svc.cluster.local 8080
  • Identity and capabilities: the running process reports the intended numeric non-root UID/GID. Its CapEff value is zero when all capabilities were dropped; if a capability was deliberately retained, only that reviewed set should appear.NoNewPrivs: 1 confirms the Linux process has the no-new-privileges flag. In Docker, also check the effective UID with docker exec … id, rather than relying on .Config.User alone. The snippets check PID 1; if a wrapper is PID 1, inspect the actual application PID instead.
  • Filesystem: a write attempt to an image directory owned by the test UID such as /var/lib/runtime-api/rootfs-write-probe fails specifically because the root is read-only, while a create-and-remove test in the declared /tmp succeeds. A different error can mean the identity or tool is wrong, so diagnose it before counting the check as passed.
  • Mounts and host access: Docker'sMounts and HostConfig show only expected volumes; Privileged is false, PID/IPC/network modes are not host, and no Docker socket, host path, or device is present. The live Kubernetes Pod shows only declared volumes, read-only config, bounded scratch space, no hostPath, and false or unset host namespace fields. Check the admitted Pod because admission may mutate the submitted object.
  • Network: from the workload, test a required service and port and confirm it succeeds; test a deliberately disallowed destination and confirm it fails. Also test inbound reachability from an approved and an unapproved source. Review effective firewall or CNI policy counters/logs alongside the probe: a failed connection alone could be a DNS or service outage, not an enforced policy.
  • Resources: Docker inspect shows the configured memory, CPU, and PID ceilings; docker stats shows current use. Kubernetes Pod description shows the admitted requests and limits. Where available, inspect cgroup v2 memory.max and cpu.max, or their cgroup v1 equivalents. In staging, apply a controlled load and confirm CPU throttling or memory enforcement at the configured boundary; do not force an OOM test on production.
  • Syscall profile: Docker inspect should show no seccomp=unconfined override (an empty override commonly means Engine default behavior). The Kubernetes Pod should specify RuntimeDefault or the approved Localhost profile. Then confirm the node runtime actually applied the profile; in a disposable test, a harmless probe for a syscall deliberately denied by that profile should return the expected permission error, while application smoke tests still pass. A Pod spec alone does not prove the node profile's content or behavior.
Docker and Kubernetes · configured limits, observed use, and cgroup readings
# Docker: configured limits plus observed use; run any load test in a safe test environment.
docker inspect --format 'memory={{.HostConfig.Memory}} nanoCpus={{.HostConfig.NanoCpus}} pids={{.HostConfig.PidsLimit}}' "$CID"
docker stats --no-stream "$CID"

# Kubernetes: inspect the admitted Pod, then check cgroup limits if the container exposes them.
kubectl describe pod "$POD" -n apps
kubectl exec -n apps "$POD" -c app -- sh -c 'cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max'
# On cgroup v1 nodes, inspect memory.limit_in_bytes and cpu.cfs_quota_us/cpu.cfs_period_us instead.

05 · Operations and review

Monitor behavior, patch the base, and check the deployed digest

Define a normal runtime baseline for each workload: expected executable paths and parent-child process relationships, effective identity and capabilities, writable directories, listening ports, and outbound peers. Alert on unexpected shells or binaries, process creation from unusual parents, privilege-changing operations, writes outside declared paths, new mounts, and unexpected network connections. Container stdout/stderr and lifecycle events are useful, but they do not by themselves provide process, filesystem, or connection telemetry. Collect relevant node/runtime security events or an approved runtime sensor, centralize them, and review alert context, workload identity, image digest, and change history. In Kubernetes, retain cluster audit logs for workload changes and API actions; Pod Events help with scheduling, admission, and restarts but are not a complete runtime activity log.

Review application output and lifecycle events alongside alerts from the node/runtime sensor that records process, privilege, file, and connection activity. In a safe staging workload, generate a controlled event for each alert rule and confirm that the alert contains the workload identity, image digest, event time, and supporting process or network context, then verify the response and retention path.

Docker and Kubernetes · review application output and lifecycle records
# Review application output and lifecycle records alongside a runtime security sensor.
docker logs --since 1h "$CID"
docker events --since 1h --filter "container=$CID"
kubectl logs -n apps "$POD" -c app --since=1h
kubectl get events -n apps --sort-by=.lastTimestamp

When the trusted base publishes a security update, rebuild from the patched base using the reviewed source and dependency inputs, scan and approve the resulting image, and record its digest. A scan is one input to release review; it cannot prove that runtime configuration, host isolation, network policy, or observed behavior is secure. For the existing build, scan, and registry permission workflow, continue to the GitLab CI and Registry Security chapter. Its supporting GitLab CI/CD YAML documentation, GitLab container-scanning documentation, and GitLab protected container repositories documentation cover the pipeline, image scan, and registry permission details.

Deploy the reviewed image by digest instead of a movable tag. After rollout, inspect each running replica's resolved image ID and compare it with the reviewed digest and the platform-specific manifest selected for that node. For multi-architecture image indexes, compare the resolved platform manifest to the recorded index and build evidence; do not assume every runtime prints the same digest format. A mismatch, missing identity, or stale replica is a release follow-up, not a cosmetic discrepancy.

Observe image IDs actually reported by running workloads
# Compare runtime-resolved image IDs with the reviewed release digest and platform manifest.
kubectl get pod "$POD" -n apps -o jsonpath='{range .status.containerStatuses[*]}{.name}{"\t"}{.image}{"\t"}{.imageID}{"\n"}{end}'

CID="<container-id>"
IMAGE_ID="$(docker inspect --format '{{.Image}}' "$CID")"
docker image inspect --format '{{json .RepoDigests}}' "$IMAGE_ID"

Revisit the deployment and host controls against the current NIST SP 800-190 Application Container Security Guide and the applicable version of the CIS Docker Benchmark. Record exceptions with their owner, rationale, compensating control, and review date. Use the benchmarks as review aids, then validate each control against the application's threat model and the actual runtime.