Updated August 2026: This article was originally published in April 2024 and has been comprehensively updated to reflect the latest container security practices, including supply chain attestation, eBPF-based runtime security, admission policy enforcement, and workload identity federation as of 2026.
Introduction
The process of protecting containerized applications from possible threats is known as container security. These containerized applications are vulnerable to more than just CVEs in base images — they face misconfigured containers, lack of isolation, supply chain attacks, runtime compromise, privilege escalation, and container escape exploits.
Container adoption is now the default for microservices architectures. Kubernetes orchestrates workloads across EKS, AKS, GKE, and self-managed clusters. With this ubiquity comes a broader attack surface and a more sophisticated threat landscape.
In this guide, we cover 12 container security best practices organized by priority — from the foundational practices that prevent the most impactful attacks, to the operational practices that maintain long-term resilience. These practices are informed by real-world incidents, CIS Kubernetes benchmarks, and the NIST SP 800-190 container security guide.
High Priority
1. Enforcing the Least Privilege Principle
The least privilege principle minimizes the potential damage caused by a compromised container. With least privilege, a workload (or user) gets access to only the services required to perform their tasks. If an attacker compromises a container, they gain minimal ability to move laterally or escalate privilege.
Implementation details:
- Run containers as non-root: Define
runAsNonRoot: trueand set a specificrunAsUserin your pod security context. Most containerized applications do not need root access. - Drop all Linux capabilities and add back only what is needed: Start with
drop: ["ALL"]and selectively add capabilities likeNET_BIND_SERVICEif the application specifically requires them. - Use read-only root filesystems: Set
readOnlyRootFilesystem: trueto prevent attackers from modifying binaries or writing malware to the container filesystem. - Limit resource access: Define CPU and memory limits to prevent resource abuse (e.g., cryptomining). Define network policies to restrict pod-to-pod communication.
- Service account scoping: Each workload should have its own Kubernetes service account with only the RBAC permissions it genuinely needs. Never use the default service account.
Extending least privilege to identity:
For human access to clusters, implement Kubernetes JIT — ephemeral kubeconfig that auto-expires. Engineers get cluster access only when needed, for as long as needed, with full audit trail. This eliminates standing kubectl access that persists indefinitely.
For workloads, use IAM Roles for Service Accounts (IRSA on EKS), Workload Identity (GKE), or AAD Pod Identity (AKS) to grant cloud permissions to pods without static credentials.
2. Ensure Secure Container Images
Vulnerable container images are prime targets for attackers. A single vulnerable dependency in a base image can affect every workload built from it. You can mitigate these risks through disciplined image hygiene.
Trusted base images:
- Obtain container images from official registries and trusted vendors only (Docker Official Images, Chainguard, Google Distroless)
- Use minimal base images — Alpine, Distroless, or Scratch images have smaller attack surfaces than full OS images (Ubuntu, Debian)
- Pin image tags to specific digests rather than mutable tags like
latest
Image scanning in CI and runtime:
- Scan images for vulnerabilities during the build phase (shift-left) — catch issues before they reach any registry
- Re-scan images in the registry continuously — new CVEs are disclosed daily, and yesterday’s clean image may have a critical vulnerability today
- Scan running container images to identify drift between what was deployed and what is currently running
Multi-stage builds:
Use multi-stage Docker builds where each stage builds upon the previous one. The final production image contains only the compiled application and its minimal runtime dependencies — no build tools, no compilers, no package managers that attackers could abuse.
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Production stage — minimal surface
FROM gcr.io/distroless/nodejs20-debian12
COPY --from=builder /app/dist /app
CMD ["/app/server.js"]
Image signing and attestation:
In 2026, best practice goes beyond scanning — it includes cryptographic attestation:
- Sign images with Sigstore/cosign: After build and scan, sign the image. This creates a verifiable chain of custody.
- Generate and attach attestation: Attach build provenance (SLSA), vulnerability scan results, and SBOM as signed attestations to the image.
- Enforce signatures at admission: Configure admission controllers (Kyverno, Connaisseur) to reject any image that lacks a valid signature or attestation.
3. Reducing the Attack Surface
A smaller attack surface means fewer potential entry points for attackers. Eliminating unnecessary processes and components reduces the risk of vulnerabilities being exploited.
Practical attack surface reduction:
- Remove unnecessary packages: If your container doesn’t need curl, wget, or bash, don’t include them. Every binary is a tool an attacker can use post-compromise.
- No package managers in production: Remove apt, apk, yum from final images. This prevents attackers from installing additional tools.
- Single process per container: Run one process per container. This limits blast radius and makes behavioral monitoring more effective — any unexpected process is immediately suspicious.
- Disable unnecessary network interfaces: If a container only needs to communicate over specific ports, bind only to those ports.
- Eliminate debug/diagnostic endpoints: Production containers should not expose profiling, debugging, or health-check endpoints that reveal internal state.
Container hardening with security contexts:
securityContext:
runAsNonRoot: true
runAsUser: 1000
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
seccompProfile:
type: RuntimeDefault
This security context eliminates privilege escalation paths, prevents filesystem modification, drops all Linux capabilities, and applies the default seccomp profile to restrict system calls.
4. Implement Network Segmentation
Network segmentation prevents lateral movement within the cluster. If one container is compromised, network policies ensure the damage is contained and other services are not affected.
Kubernetes Network Policies:
- Default deny all ingress and egress: Start with a deny-all policy for each namespace, then explicitly allow only the communication paths your application requires.
- Namespace isolation: Separate environments (dev, staging, prod) into different namespaces with strict network boundaries.
- Pod-level policies: Define policies at the pod selector level, not just namespace level. A compromised pod should not be able to reach unrelated services in the same namespace.
Cilium for advanced network security:
In 2026, Cilium (eBPF-based networking) has become the standard CNI for security-focused Kubernetes deployments. Beyond traditional L3/L4 policies, Cilium provides:
- L7 policy enforcement: Restrict traffic at the HTTP/gRPC level (allow GET /api/health but deny POST /admin)
- DNS-aware policies: Control egress based on DNS names, not just IP addresses
- Identity-based segmentation: Define policies based on pod identity rather than IP addresses (which are ephemeral in Kubernetes)
- Network flow visibility: Complete visibility into every connection attempt, successful or blocked
5. Secrets Management
Storing sensitive information like usernames, passwords, or API keys in your containers is a significant security risk that most organizations overlook. Container images in registries can be pulled by anyone with access, exposing all embedded secrets.
Best practices for container secrets:
- Never embed secrets in images: Not in environment variables baked into the Dockerfile, not in configuration files copied into the image, not in code committed to the repository.
- Use external secrets management: Integrate with HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or GCP Secret Manager. Secrets are injected at runtime, not at build time.
- Kubernetes secrets with encryption at rest: While Kubernetes Secrets are base64-encoded (not encrypted) by default, enable encryption at rest and consider using the Secrets Store CSI Driver to mount secrets from external providers.
- Rotate secrets automatically: Implement automated rotation. When a secret is compromised, the rotation window determines your exposure time.
- Eliminate shared database passwords: Rather than sharing a single database credential across all pods, use Database JIT access — each session gets a unique, identity-stamped, time-bound credential. No shared passwords to leak.
Medium Priority
6. Integrating Robust Container Security Tools
Container security tools provide vulnerability scanning, runtime protection, policy enforcement, and threat detection capabilities that enhance your overall security posture.
Evaluating container security tooling:
When selecting a container security platform, consider:
- Coverage depth: Does it cover the full lifecycle — build, registry, deployment, runtime? Or only one stage?
- Multi-cluster support: Can it handle EKS, AKS, GKE, and self-managed clusters from a single console?
- Integration with your existing workflow: Does it post findings as PR comments? Does it integrate with Slack, Jira, PagerDuty?
- Contextual prioritization: Does it correlate container vulnerabilities with identity permissions, network exposure, and data sensitivity? A critical CVE in an air-gapped pod with no IAM role is different from the same CVE on an internet-facing pod with admin access.
- Signal-to-noise ratio: How many findings are actionable versus noise? Adaptive notification management (auto-snooze, deduplication) prevents alert fatigue.
Cloudanix’s container security provides integrated scanning across the full lifecycle, correlated with the broader cloud security graph — so container findings are enriched with identity context, network reachability, and compliance mapping from the same platform that handles CSPM and CIEM.
7. Updating and Patching Regularly
Addressing vulnerabilities promptly and applying security patches reduces the risk of attackers exploiting known issues. In the container world, patching means rebuilding images — not running apt update inside a running container.
Patching strategy for containers:
- Automate base image updates: Use tools like Renovate or Dependabot to automatically propose PRs when base image updates are available.
- Rebuild, don’t patch in place: Containers are immutable. When a vulnerability is discovered, rebuild the image with the patched dependency, push to registry, and redeploy. Never SSH into a running container to apply patches.
- Define SLAs by severity: Critical vulnerabilities with known exploits: patch within 24–72 hours. High vulnerabilities: patch within 1–2 weeks. Medium/Low: address in the next release cycle.
- Track patch coverage: Monitor what percentage of your running containers are built from the latest patched image. Stale deployments with unpatched images are a common blind spot.
8. Protecting Container Orchestration
Securing your container orchestration platform (Kubernetes) is compulsory — it manages and controls container deployments, scaling, and networking. A compromised cluster API server gives attackers control over every workload.
Kubernetes control plane security:
- API server access control: Restrict API server access to specific CIDR ranges. Use RBAC with least-privilege roles. Enable audit logging for all API calls.
- etcd encryption: Enable encryption at rest for etcd (the Kubernetes backing store). All secrets, configmaps, and cluster state lives in etcd.
- Admission controllers: Deploy and configure admission controllers that enforce security policies at deployment time:
- Kyverno: Policy-as-YAML, no new language to learn. Generate, validate, and mutate resources.
- OPA Gatekeeper: Rego-based policies for complex logic. Constraint templates provide reusability.
- Pod Security Standards (PSS): Enforce Baseline or Restricted security standards at the namespace level. Privileged pods should be the exception, not the default.
- RBAC hygiene: Regularly audit RBAC bindings. Remove stale bindings. Never grant cluster-admin to service accounts. Use namespace-scoped roles rather than cluster roles where possible.
Securing managed Kubernetes:
For managed services (EKS, AKS, GKE):
- Keep the cluster version current (within one minor version of latest)
- Enable control plane logging and ship logs to your SIEM
- Use private cluster endpoints where possible — no public API server access
- Enable Security Groups for Pods (EKS) or similar network isolation at the pod level
9. Admission Policy Enforcement
Beyond basic admission controllers, implement comprehensive policy enforcement that catches misconfigurations before they become running workloads.
Policy categories to enforce:
- Image policies: Only allow images from approved registries; require image signatures; block images with critical CVEs
- Workload policies: Require security contexts; block privileged containers; enforce resource limits; require liveness/readiness probes
- Network policies: Require a NetworkPolicy for every namespace; block default-allow configurations
- Label and annotation policies: Require ownership labels (team, service, environment) for accountability
- Compliance policies: Map organizational compliance requirements (SOC 2, HIPAA, PCI) directly to admission policies
Low Priority
10. Preparing an Incident Response Plan
Having an incident response plan that outlines procedures for detection, containment, eradication, and recovery helps you respond effectively to container-specific security incidents.
Container-specific IR considerations:
- Detection: What signals indicate a container is compromised? Unexpected processes, unusual network connections, filesystem writes to read-only paths, or anomalous API calls.
- Containment: How do you isolate a compromised pod without affecting the rest of the service? Network policy quarantine, service mesh circuit-breaking, or pod deletion with investigation of the underlying node.
- Evidence preservation: Containers are ephemeral — if you kill the pod, you lose the evidence. Capture container filesystem state, memory dump (if possible), and all relevant logs before remediation.
- Scope assessment: If one pod is compromised, what else can the attacker reach? Service account permissions, network access, secrets mounted, and external service connections determine blast radius.
11. Regular Audits and Compliance
Conducting regular security audits of your containerized applications and infrastructure helps identify potential threats and vulnerabilities in your container environment.
Audit areas for containers:
- CIS Kubernetes Benchmark: Run automated CIS benchmark checks against your clusters regularly (kube-bench)
- Image freshness: What percentage of running images are more than 30/60/90 days old?
- RBAC audit: Who has access to what? Are there stale bindings? Are there cluster-admin bindings that shouldn’t exist?
- Network policy coverage: What percentage of namespaces have explicit network policies?
- Secrets audit: Are any secrets mounted that are no longer needed? Are any secrets older than the rotation window?
- Compliance mapping: Map your container security posture to relevant frameworks (SOC 2, HIPAA, PCI, NIST) and generate audit-ready evidence
12. Continuous Integration/Delivery Security and Runtime Monitoring
Integrating security checks into your CI/CD pipelines helps identify threats and vulnerabilities early in your deployment lifecycle.
CI/CD pipeline security:
- Scan at every stage: Source code (SAST), dependencies (SCA), container images (vulnerability scan), IaC (policy compliance), and deployment manifests (admission pre-check)
- Break the build on critical issues: Define clear thresholds. A critical CVE in a production image should fail the pipeline.
- Generate SBOM and sign artifacts: Every successful build should produce a signed SBOM and signed container image.
- Secure the pipeline itself: CI/CD runners are high-value targets. Use ephemeral runners, restrict runner network access, and grant minimum IAM permissions. Ensure no long-lived credentials are stored in pipeline configurations.
Runtime monitoring and threat detection:
- eBPF-based monitoring: Modern runtime security uses eBPF to observe system calls, network connections, and file access at the kernel level — without the overhead of traditional agents. This provides deep visibility into container behavior.
- Behavioral baselines: Establish what “normal” looks like for each container (expected processes, network connections, file access patterns). Any deviation from baseline triggers an alert.
- Intrusion detection/prevention (IDS/IPS): Detect and block known attack patterns — container escape attempts, cryptominer execution, reverse shells, and lateral movement.
- Workload identity monitoring: Track which workload identities are being used, from where, and for what. Anomalous credential usage (a pod making IAM calls it never made before) is a high-fidelity signal.
Bringing It All Together
Security is an ongoing process, and the specific priority of these practices may vary depending on your unique risk profile and threat landscape. Continuously evaluate your security posture, adapt your strategies, and leverage these best practices to maintain a secure and resilient cloud container environment.
The most effective container security programs share a common trait: they don’t treat container security in isolation. A container vulnerability correlated with an over-privileged service account, internet exposure, and access to a sensitive database is a critical attack path. The same vulnerability in an air-gapped pod with no permissions is informational noise.
Along with CSPM and CIEM, Cloudanix provides an integrated container security platform that places your container findings on the same security graph as identity, posture, and code findings. Your team gets a real-time view of threats and vulnerabilities with contextual severity — so they can address the highest-risk findings first. Getting started takes less than five minutes with agentless onboarding.