Accent colour
 
Shortcuts: press ?
 

Container Security: A Guide for Docker and Kubernetes

Muhammad Tahir December 01, 2026

The dashboard with no password

In 2018, a cloud security firm scanning the internet found Tesla's Kubernetes dashboard sitting open to anyone who knew where to look — no password, and inside it, credentials for the company's cloud account. Attackers had already used them to run cryptocurrency mining software on Tesla's infrastructure. Nobody had broken into a server or exploited a zero-day. Someone had left the front door open, and someone else walked in.

That story still gets told at security conferences because it captures the central fact about containers: most container breaches are ordinary misconfigurations, repeated at scale. An image ships with a known vulnerability nobody scanned for. A pod runs as root because nobody set a user. A cluster accepts any image because nobody turned on admission control. Each mistake looks small on its own. Together they hand an attacker a straight path from a public web page to your cloud account.

Containers also change what a mistake costs. In a cluster, one compromised container shares a kernel with every other container on the same host, talks to the cluster API, and may hold a service account token that can read secrets across namespaces. This guide walks through the fix the way a team actually builds it: the image, then the runtime, then the cluster, then the network, then the secrets, then the watching. It draws on NIST SP 800-190, the Application Container Security Guide and the Kubernetes Pod Security Standards.

What a container actually shares with the host

A container looks like a small virtual machine and behaves like one from the outside, but the resemblance stops at the kernel. A virtual machine runs its own kernel on emulated hardware. A container is a set of Linux processes running on the host's kernel, fenced off by two kernel features: namespaces, which control what a process can see, and control groups, which control what resources it can use.

That shared kernel is the whole security story. A kernel vulnerability that lets a process escape its namespace is a vulnerability in every container on that host at once. This is why NIST's guide treats the host as one of the five components to protect, alongside images, registries, orchestrators and the containers themselves. Patch the host kernel on the same schedule you patch the application, because the host is part of the application now.

The shared kernel also explains why a container is not a security boundary in the way a virtual machine is. It is an isolation mechanism with a known set of escapes, and the escapes are exactly what an attacker looks for: a container running as root, a container with extra Linux capabilities, a container with the host's Docker socket mounted, a container sharing the host's process or network namespace. Every one of those is a configuration choice somebody made, usually for convenience, usually years ago, usually forgotten.

Start with the image: small, pinned and scanned

Everything downstream inherits the image. If the image ships a vulnerable library, every pod running it is vulnerable. If it ships a secret baked into a layer, every copy carries it. Image hygiene is unglamorous work, and it is where most container security programmes should start.

First, use a small, trusted base image. A full operating system image carries hundreds of packages your application will never touch, and each one is a potential vulnerability. A minimal base — Alpine, a slim Debian variant, or a distroless image that contains only the application and its runtime — shrinks that surface dramatically. Distroless images go furthest: no shell, no package manager, nothing for an intruder to use.

Second, pin what you build from. A Dockerfile that says FROM node:22 builds a different image next month than it builds today, because the tag moves. Pin the image digest instead — the long sha256: hash that identifies one exact build. Tags are labels. Digests are fingerprints.

Third, build in stages. A multi-stage Dockerfile compiles the application in one image, with all the compilers and build tools, and copies only the finished artefact into a clean runtime image. The build tools never reach production, and the runtime image ends up a tenth the size, with a tenth of the packages to patch.

Fourth, run as a non-root user. Add a USER directive to the Dockerfile, or set the user in the pod specification. This one line blocks a whole class of attacks, because many container escapes only work when the process inside is already privileged. It breaks applications that assume they can write anywhere or bind to a low port, which is why teams put it off. Fix the application. Do not give it root.

Fifth, scan every image before it is promoted, and scan it again later. A scanner such as Trivy or Grype checks the image's packages against vulnerability databases, and wired into the build pipeline it fails a build with a new critical vulnerability before it reaches the registry. Then keep scanning the images already in the registry, because new vulnerabilities are disclosed about old packages every week. An image that was clean in March can be vulnerable by June without anyone touching it.

Sign what you ship, and keep a list of what is inside it

Scanning catches known vulnerabilities. It does nothing about whether the image you are about to run is the image your pipeline built. An attacker who can push a modified image to your registry, or tamper with one in transit, does not need a vulnerability at all.

Signing closes that gap. When the build pipeline finishes an image, it signs it with a private key. Before the cluster runs an image, an admission controller checks the signature, and an unsigned image, or one signed by the wrong key, is refused. The tooling most teams use is Sigstore's cosign, which is free and open source, and the policy check is usually done by Kyverno or Open Policy Agent's Gatekeeper, both of which run as admission controllers in the cluster.

Alongside the signature, generate a software bill of materials, or SBOM: a machine-readable list of every component inside the image, with library names and versions. It sounds like paperwork, but it is paperwork that becomes priceless the day a new vulnerability is announced. When Log4Shell hit in December 2021, teams with SBOMs could search their inventory and know within minutes which images contained the vulnerable library. Teams without them spent days grepping through registries. Generate the SBOM at build time and store it with the image.

One more habit: mirror the images you use into a private registry you control, scan them there, sign them there, and let the cluster pull only from there.

The runtime: least privilege, enforced by the cluster

The image is what you ship. The runtime is what it is allowed to do once it is running, and Kubernetes builds the controls for that into the platform.

The starting point is the Pod Security Standards, which define three profiles. Privileged is unrestricted, meant only for system workloads like networking plugins. Baseline blocks known privilege escalations and is the minimum any workload should meet. Restricted follows current hardening practice: non-root users, no privilege escalation, dropped capabilities, an explicit seccomp profile, and a limited set of volume types. It is the profile to aim for, enforced by Pod Security Admission, built into Kubernetes since version 1.25.

Enforcement happens through namespace labels: label a namespace to enforce the restricted profile, and any pod that violates it is rejected at admission, before it runs. Start in warn or audit mode for a week so you can see what would be rejected without breaking anything, then switch to enforce. Turning on enforcement on a Friday without the warn phase is how you take down a production service.

A pod that passes the restricted profile looks like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: web
        image: registry.example.com/shop/web:1.4.2
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]

runAsNonRoot and a numeric runAsUser mean the process is not root. allowPrivilegeEscalation: false stops a process from gaining more privilege than it started with. Dropping all Linux capabilities removes abilities like changing file ownership or binding to low ports; add back only what the application genuinely needs, usually none. The RuntimeDefault seccomp profile filters the system calls the container can make, and readOnlyRootFilesystem mounts the filesystem read-only, so an attacker who gets in cannot write a backdoor binary.

One thing to check separately: the read-only root filesystem is not actually required by the restricted profile, even though it should be, so enforce it in your pipeline or policy. And seccomp's RuntimeDefault is the runtime's default profile, not a custom allowlist — good enough for most workloads, and no reason to delay.

The cluster itself: identity, admission and the API server

A hardened pod means little if the cluster around it is wide open. The Kubernetes API server can create pods, read secrets, and change anything, and it is reachable over the network by design. Protecting it is a separate job from protecting the pods.

Start with role-based access control, or RBAC. Every person and every service account should have the smallest set of permissions that lets it do its job, and nothing more. The default service account in a namespace should not be able to list secrets cluster-wide, and yet in many clusters it can, because nobody changed the defaults. Audit your roles with kubectl auth can-i --list and remove the permissions that make you wince. Pay special attention to service accounts that can create pods: creating a pod is effectively the ability to run code, and a service account that can create a privileged pod can escape the cluster entirely.

Keep the human side tight as well: no shared admin credential, cluster access through your identity provider with groups mapped to roles, so removing someone from the company removes their access automatically. Enable audit logging on the API server, and ship the logs somewhere that alerts on the interesting events: a new cluster-admin binding, a secret read by an unfamiliar account, a pod created outside the usual namespaces.

The control plane itself needs hardening too. The CIS Kubernetes Benchmark is the checklist most teams use: it scores the configuration of the API server, etcd, the kubelet and the scheduler against a long list of recommended settings. The tool kube-bench runs the benchmark against a cluster and produces a pass/fail report. Run it regularly, and treat its failures as a backlog, not a one-off exercise. Managed Kubernetes services handle much of the control plane for you, but the parts you still own — RBAC, admission, network policy — are the parts attackers target.

Admission control is the last gate before a pod runs, and it is where policy becomes real. Pod Security Admission handles the runtime settings. A policy engine like Kyverno or Gatekeeper handles everything else: requiring signed images, forbidding the :latest tag, blocking images from public registries. Anything you would reject in a code review should be rejected by admission control instead, because admission control never gets tired. If you want a deeper treatment of identity in cloud systems, our guide to identity and access management covers the same least-privilege thinking applied to cloud accounts and human users.

The network: assume the pod next door is hostile

Kubernetes networking has a default that surprises newcomers: by default, any pod can talk to any other pod in the cluster. There is no firewall between them. A compromised web pod can reach the database, the cache, the internal admin service and the metadata endpoint, all without crossing a single control. That default is convenient for development and dangerous in production.

NetworkPolicy is the fix, and it works like a firewall for pods: a policy says which pods can talk to which other pods, on which ports, and everything else is denied. Start with a default-deny policy in each namespace, then add explicit policies for the traffic each application genuinely needs. The web tier talks to the application tier on port 8080; the application tier talks to the database on port 5432; nothing else talks to anything. When a pod is compromised, the attacker's lateral movement stops at the first policy boundary.

Egress deserves the same attention as ingress. A container that can reach the open internet can download malware, exfiltrate data, or join a botnet, so restrict egress to the destinations the application needs: your APIs, your package registries, your monitoring endpoints. Also block the cloud metadata endpoint at the network layer — on cloud-hosted clusters, a pod that can reach it can sometimes obtain the node's cloud credentials.

For traffic between services, mutual TLS is the standard. In a service mesh, every connection between pods is encrypted and authenticated in both directions, so a compromised pod cannot impersonate another service. A mesh adds operational complexity, and not every team needs one on day one, but if you handle payment data or health records it is hard to argue against. At minimum, treat the cluster network as untrusted, not as a safe internal zone. The zero-trust idea — never trust a connection just because it comes from inside — applies to pods as much as it does to people, and our article on zero trust architecture explains the thinking behind it.

Secrets and identity: stop passing keys around

Secrets are the quiet failure mode of container security. They sit baked into image layers, in plain text in environment variables, and committed to version control in deployment manifests. And because containers are copied, moved and scaled so easily, a secret that leaks once leaks everywhere.

The first rule is the simplest: never put a secret in an image. Not in an environment variable in the Dockerfile, not in a config file copied during the build, not in a layer you think nobody will look at. Image layers are trivially inspectable, and the same goes for version control: a secret committed to a repository will be found, sooner or later, by a scanner or a former employee.

Instead, inject secrets at runtime, from a secret manager, and only into the containers that need them. Kubernetes has a built-in Secret object, but it is only base64-encoded by default, not encrypted, so enable encryption at rest for etcd or use an external secret manager such as HashiCorp Vault, AWS Secrets Manager or Azure Key Vault, synced into the cluster by a tool like External Secrets Operator. Mount secrets as files rather than environment variables where you can, because environment variables show up in process listings and crash dumps. And give each secret the shortest life you can: rotate them regularly, and prefer short-lived credentials over long-lived ones.

Workload identity is the bigger idea underneath all of this. Instead of handing a pod a static cloud credential — a key that works forever, from anywhere, until someone remembers to revoke it — give the pod an identity the cloud provider recognises, and let it request short-lived tokens when it needs them. On AWS this is IAM Roles for Service Accounts, and the open standard SPIFFE gives workloads a portable identity across providers. Our CI and CD guide covers how to keep secrets out of build pipelines, which is where they most often leak: CI/CD pipelines explained.

Watching it run: detection and response

Prevention is the first six sections of this guide. Detection catches what prevention misses, and it matters because prevention always misses something. The question is not whether something will get through, but whether you will notice.

Runtime detection tools watch what containers actually do, rather than what they were configured to do. Falco, the open source standard here, watches system calls and alerts when a container does something it should not: spawning a shell, opening a connection to an unusual address, writing to a sensitive path. The cloud providers offer their own versions — GuardDuty for EKS, Defender for Containers on Azure — built on the same idea: a baseline of normal behaviour, and an alert when something leaves it.

The alerts are only useful if someone acts on them, so detection needs to be wired into the same incident response process as everything else. Decide in advance what happens when a container starts behaving strangely: who gets paged, how the pod is isolated, how you preserve evidence before you delete it. Then test the whole thing: run a tabletop exercise where a team member plays the attacker and see how far they get. Security that has never been tested is a hope, not a control.

Questions teams ask before they harden a cluster

Do we need to secure containers if we already have a firewall and a WAF?

Yes. The firewall and the WAF protect the edge, while most container attacks start inside the edge or bypass it entirely. A compromised dependency, a leaked credential, a misconfigured API — none of those go through your firewall. Container security protects the workloads themselves, a different layer that does not substitute for the perimeter.

Is running as root really that bad if the container is isolated?

Yes. Root inside a container is not the same as root on the host, but many known container escapes require root inside the container as a starting point, and a root process can do far more damage than a non-root one. Running as a non-root user is a one-line change that removes a whole class of attacks, and the restricted Pod Security Standard requires it.

Should small teams bother with image signing?

Sooner than they think. The tooling is free and the setup is a few hours of work. The question is not how big your team is; it is what happens when someone pushes a tampered image to your registry. If the answer is "we would run it without noticing", signing is worth doing, starting with the images that handle sensitive data or face the internet.

How do we harden a cluster that is already running production workloads?

In stages. Turn on Pod Security Admission in warn mode first and fix what it flags. Add NetworkPolicy one namespace at a time, starting with the least sensitive. Scan images and fix the critical findings before you add a blocking gate. A hardening programme that takes down production on its first day does not get a second day.

Your first 30 days: a hardeni

Was this article helpful?

Muhammad Tahir

Author

 

Get new articles by email

 

Comments