Home  /  Blog  /  Container Security: Docker and Kubernetes Best Practices

● Cloud Security

Container Security: Docker and Kubernetes Best Practices

Containers and Kubernetes power most modern Indian SaaS. They also concentrate risk: a compromised image affects every cluster that runs it, a permissive Kubernetes RBAC binding compromises every workload in the namespace. Here is the practical container security baseline for DevSecOps teams.

Published 23 May 2026 9 min read Codesecure Cloud Security Team Cloud Security

Key Takeaways

  • Image hygiene first. Minimal base images, no embedded secrets, scanned in CI with Trivy / Grype / Snyk, signed with cosign.
  • Dockerfile best practice matters: non-root user, multi-stage builds, explicit FROM versions, no curl-bash in production builds.
  • Kubernetes RBAC is unforgiving. Wildcards in verbs or resources, broad ClusterRoleBindings, and pods/exec on Tier-0 pods are all routine escalation primitives.
  • Secrets in K8s native Secrets are base64, not encrypted at rest by default. Encryption providers (KMS) or external secret managers (Vault, Sealed Secrets, ESO) are recommended.
  • Runtime defence with Falco or commercial equivalents catches the techniques RBAC and image scanning miss.

Image Hygiene: Build, Scan, Sign

Container security starts at build time. The image you ship is the artefact attackers will inherit. Minimal base images (distroless, Alpine, Wolfi, scratch where possible) reduce attack surface. Multi-stage Dockerfiles ensure build tools, dependencies, source code and credentials used during build do not end up in the final image.

Every image must be scanned in CI for known-vulnerable packages. Trivy (open source), Grype (open source), Snyk Container, Anchore Enterprise, and the scanning built into Azure Container Registry, AWS ECR and Google Artifact Registry all do this. Fail builds on Critical and High CVEs above a defined threshold; treat older Medium CVEs through scheduled rebase rather than blocking deploys.

Image Signing and Supply Chain

Image signing (cosign with Sigstore, Notary v2) cryptographically binds an image to its source. Cluster admission policies (Kyverno, OPA Gatekeeper) verify signatures before allowing the image to run. Without signing, an attacker who pushes to your registry can deploy unsigned malicious images. SBOM (Software Bill of Materials) generation with Syft or Anchore documents what is in each image and feeds vulnerability tracking. The supply chain security story (SLSA framework, in-toto, Sigstore) has matured rapidly since 2023 and is achievable for any team with a CI pipeline.

Dockerfile Best Practices

Dockerfiles encode operational and security decisions in code. The recurring issues we see: USER root retained throughout, packages installed without --no-install-recommends, full source tree COPYed when only a subset is needed, embedded secrets via ARG or ENV that persist in the image history, curl-pipe-bash for tool installation, and ADD https://... which obscures provenance.

  • Use a specific base image tag, not :latest. Pin to a digest where reproducibility matters.
  • Multi-stage builds with one stage for build dependencies and one stage for the slim runtime
  • USER directive to a non-root account. Most modern base images include a non-root user.
  • Minimal RUN instructions with --no-install-recommends, package cleanup in the same layer
  • No secrets in ENV or ARG. Use build-time secret mounts (BuildKit --secret) or runtime secret injection.
  • HEALTHCHECK defined for production images so the orchestrator knows when the container is ready.
  • EXPOSE only the ports the application actually needs.
  • WORKDIR set explicitly so subsequent commands behave predictably.

Need a Cloud Security Assessment?

Codesecure runs ISO/IEC 27001:2022 certified cloud security assessments and pentest across AWS, Azure and GCP for Indian enterprises. Named OSCP consultants, CIS and CSA mapping, fixed-price proposals, free retest within 90 days.

See Cloud Services →

Kubernetes RBAC: Where Most Findings Live

Kubernetes RBAC is powerful and unforgiving. A single wildcard in a Role or ClusterRole effectively grants admin within the scope. Privilege escalation primitives include pods/exec on any pod (lets the holder shell into another workload), secrets/get or list at namespace or cluster level (exposes credentials), pods create (allows scheduling a privileged pod and node compromise), impersonate verbs (allows assuming any other identity), rolebindings or clusterrolebindings create (allows self-granting cluster-admin), and escalate on roles (allows promotion of existing roles).

Tools to enumerate and visualise: rbac-police, kubectl-who-can, rakkess, rbac-tool, KubeHound. A clean RBAC pass on a typical Indian SaaS cluster surfaces 3 to 10 escalation paths from default service-account positions. Most are closeable in days; the workflow to keep them closed (RBAC reviews on every change) is the longer programme.

Network Policies and Pod Security Standards

Default Kubernetes networking allows any pod to reach any other pod. NetworkPolicy resources restrict this, but only when the CNI (Calico, Cilium, Weave) enforces them. Modern Kubernetes deployments should default-deny ingress and egress per namespace and explicitly allow only what is needed.

Pod Security Standards (PSS) replace the deprecated Pod Security Policies. Three levels: privileged (no restrictions), baseline (prevent known privilege escalations), restricted (the strongest practical posture for most workloads). Enforce restricted at the namespace level for application workloads, baseline for kube-system and selected platform namespaces, privileged only where genuinely required and documented. Enforcement is via the in-built admission controller or via OPA Gatekeeper / Kyverno policies.

Secrets Management in Kubernetes

Native Kubernetes Secrets are base64-encoded, not encrypted at rest by default. Anyone with read access to etcd or to the secret in the API has the value. Three approaches mitigate this.

Encryption at rest providers: configure the API server with EncryptionConfiguration pointing to a KMS (AWS KMS, Azure Key Vault, GCP KMS, or Vault as a KMS plugin). The secret is encrypted before persisting to etcd. This is the lightest-touch improvement and is supported on all managed Kubernetes services.

External Secret Operators: External Secrets Operator (ESO) or HashiCorp Vault Agent Injector pull secrets from an external store (Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager) and project them into pods at runtime. The Kubernetes Secret is a pointer, not the actual secret.

Sealed Secrets (Bitnami) encrypt the secret in GitOps repository form so that only the cluster's sealed-secrets controller can decrypt. Useful for GitOps workflows where secrets must live alongside other manifests.

CSPM, IAM Cleanup or Audit Pressure?

Whether you need a CSPM deployment, an IAM rationalisation, a SOC 2 or ISO 27001 cloud control evidence pack, or a quick second-opinion on a finding, our cloud security lead is available for a 30-minute free scoping call.

Talk to a Cloud Lead →

Runtime Security: Falco and Beyond

Image scanning catches known-vulnerable packages. RBAC controls who can do what. Runtime security catches what those layers miss: a container that starts spawning unexpected processes, a pod that opens a shell, an outbound connection to an unexpected destination, a file write to a sensitive path, a privilege escalation attempt.

Falco (CNCF graduated, open source) is the canonical runtime security tool. It uses eBPF (or, on older kernels, a kernel module) to capture syscalls and matches them against a rules library. The default ruleset covers most well-known techniques; teams typically tune it to reduce noise from legitimate operations. Commercial alternatives (Sysdig Secure, Aqua Security, Wiz Runtime, Lacework) bundle Falco-like detection with management consoles, multi-cluster reporting and SOAR integration.

Runtime alerts feed the SIEM. The detection-to-response loop should be measured in minutes. A Kubernetes cluster with active runtime detection but no integrated response is theatre.

Image Registry and Supply Chain Attacks

The image registry (Docker Hub, ECR, ACR, GAR, Harbor, JFrog Artifactory) is a target. A compromise of the registry or of the credentials that push to it lets the attacker substitute malicious images that the cluster will accept. Treat registry credentials as Tier 0, scope push permissions narrowly (a CI service account, not human developers), audit push events, and require signed images for production deployment.

Supply chain attacks operate on dependencies. Malicious npm packages, PyPI typosquats, compromised GitHub Actions, and the recurring lesson from xz, eslint-scope and event-stream incidents is that any dependency can become an attacker. Mitigation: dependency pinning to versions or hashes, SBOM generation and review, allowlisted package mirrors for sensitive environments, and continuous monitoring of declared dependencies for advisories. Tools like Dependabot, Renovate, Snyk Open Source and OSSF Scorecard automate parts of this.

SHARE

Frequently Asked Questions

Do I need both image scanning and runtime security?

For production, yes. Image scanning catches known-vulnerable packages before deployment. Runtime catches workload behaviour after deployment, including techniques that no static scan can detect (zero-day exploit attempts, abnormal process execution, lateral movement). Together they cover prevention and detection.

Can I use just managed Kubernetes (EKS, AKS, GKE) defaults?

Managed Kubernetes gives you a hardened control plane, which is meaningful. You still own everything above the API: RBAC, NetworkPolicy, Pod Security, image security, runtime defence. The control plane is one layer; the workload security is yours.

Is Docker Desktop or Docker Swarm in scope?

Docker Desktop is a developer environment, not a production runtime. Docker Swarm is in production at some organisations but has lost share to Kubernetes. The image security and Dockerfile practices apply to both; the orchestrator-specific guidance (RBAC, NetworkPolicy) is Kubernetes-specific.

How do you handle compliance for container workloads?

Container findings map to ISO/IEC 27001:2022 Annex A (A.5, A.8), SOC 2 CC6 and CC7, CIS Benchmarks for Docker and Kubernetes, NSA / CISA Kubernetes Hardening Guidance, and OWASP Kubernetes Top 10. Codesecure container assessments produce compliance-mapped reports.

How long does a container security uplift take?

For a single application moving from default Docker images to a hardened baseline: 2 to 4 weeks. For a platform team rolling baseline policies across the cluster: 6 to 10 weeks. For enterprise-wide container security programme covering multiple clusters: 12 to 24 weeks. Codesecure delivers phased programmes with measurable milestones.

Do you do container penetration testing?

Yes. See our Kubernetes and container security testing guide. Container pentest covers cluster enumeration, RBAC abuse, etcd exposure, pod escape, image scanning, network policies, and integration with the underlying cloud account. Reports map to CIS, NSA / CISA and OWASP standards.

CS

Codesecure Cloud Security Team

OSCP / CCSP / AWS and Azure Certified Cloud Engineers

Codesecure Solutions is ISO/IEC 27001:2022 certified and delivers cloud security assessments, CSPM design, IAM rationalisation, container and Kubernetes hardening, and cloud pentest across AWS, Azure and GCP. Named consultants with OSCP, CCSP, AWS Security Specialty and Azure Security Engineer certifications. 150+ engagements delivered across India, Singapore, UAE and the Middle East.

✓ ISO/IEC 27001:2022 Certified

Ship Containers Without Shipping Risk

Codesecure helps Indian SaaS, fintech and enterprise customers harden Docker images, Kubernetes clusters and the surrounding CI / supply chain. ISO/IEC 27001:2022 certified delivery, named OSCP and CKS consultants, free retest within 90 days.