Harden your Docker containers and Kubernetes deployments with comprehensive security controls covering image scanning, runtime protection, network policies, and supply chain integrity.
## ROLE
You are a container security engineer with extensive experience hardening Docker, Kubernetes, and container orchestration platforms for [ENVIRONMENT TYPE: production SaaS / regulated enterprise / startup / government / financial services]. You are certified in CKS (Certified Kubernetes Security Specialist) and have deep knowledge of container attack surfaces.
## OBJECTIVE
Create a comprehensive container security hardening plan for [APPLICATION NAME] running [NUMBER] containerized services on [ORCHESTRATOR: Docker Compose / Kubernetes / ECS / Cloud Run / Nomad / Docker Swarm]. The current container infrastructure uses [BASE IMAGES: ubuntu / alpine / distroless / scratch / node / python / golang / custom] and is deployed via [CI/CD: GitHub Actions / GitLab CI / Jenkins / ArgoCD / Flux].
## TASK
### Image Security
**Base Image Selection:**
- Use minimal base images: prefer [DISTROLESS / ALPINE / SCRATCH] over full OS images
- Pin exact image digests instead of mutable tags: `FROM [IMAGE]@sha256:[DIGEST]` not `FROM [IMAGE]:latest`
- Maintain an approved base image registry at [REGISTRY: ECR / GCR / ACR / Docker Hub / Harbor / Artifactory]
- Scan base images weekly for new CVEs even without application changes
**Dockerfile Hardening for [SERVICE NAME]:**
```dockerfile
# Multi-stage build to exclude build tools from production image
FROM [BUILD_IMAGE] AS builder
WORKDIR /app
COPY [DEPENDENCY_FILES] .
RUN [INSTALL_DEPENDENCIES]
COPY . .
RUN [BUILD_COMMAND]
FROM [MINIMAL_BASE_IMAGE]
# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Copy only production artifacts
COPY --from=builder /app/[BUILD_OUTPUT] /app/
# Set ownership
RUN chown -R appuser:appgroup /app
# Drop all capabilities
USER appuser
WORKDIR /app
# Health check
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD [HEALTH_CHECK_COMMAND]
EXPOSE [PORT]
ENTRYPOINT ["[BINARY]"]
```
**Critical Dockerfile rules:**
- NEVER run as root in production containers
- NEVER use `ADD` when `COPY` suffices (ADD can fetch remote URLs and extract archives)
- NEVER store secrets in image layers (no `ENV SECRET_KEY=...` or `COPY .env`)
- Use `.dockerignore` to exclude: `.git`, `.env`, `node_modules`, test files, documentation, CI configs
- Install only production dependencies: `npm ci --omit=dev` / `pip install --no-dev` / equivalent
- Remove package managers and shells in the final stage if not needed for debugging
**Image Scanning Pipeline:**
Integrate vulnerability scanning at multiple stages:
1. **Developer workstation**: [SCANNER: Trivy / Snyk / Grype] pre-commit hook for Dockerfile linting
2. **CI pipeline**: Scan every image build, fail pipeline on [SEVERITY THRESHOLD: critical / high / medium]
3. **Registry**: Continuous scanning of stored images with [REGISTRY SCANNER: ECR scanning / Harbor / Prisma Cloud]
4. **Runtime**: Admission controller rejects unscanned or non-compliant images at deploy time
### Runtime Security
**Container Runtime Hardening:**
```yaml
# Security context for [SERVICE NAME]
securityContext:
runAsNonRoot: true
runAsUser: [UID]
runAsGroup: [GID]
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
add: [ONLY_IF_ABSOLUTELY_NEEDED]
seccompProfile:
type: RuntimeDefault
```
**Resource Limits (prevent resource exhaustion attacks):**
```yaml
resources:
requests:
memory: "[REQUEST_MEMORY]"
cpu: "[REQUEST_CPU]"
limits:
memory: "[LIMIT_MEMORY]"
cpu: "[LIMIT_CPU]"
ephemeral-storage: "[STORAGE_LIMIT]"
```
**Read-only filesystem with explicit writable mounts:**
```yaml
volumeMounts:
- name: tmp
mountPath: /tmp
- name: app-cache
mountPath: /app/[CACHE_DIR]
volumes:
- name: tmp
emptyDir:
sizeLimit: [SIZE]
- name: app-cache
emptyDir:
sizeLimit: [SIZE]
```
### Network Security
**Network Policies (Kubernetes):**
```yaml
# Default deny all ingress and egress for namespace [NAMESPACE]
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: [NAMESPACE]
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
# Allow specific communication for [SERVICE NAME]
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-[SERVICE_NAME]
namespace: [NAMESPACE]
spec:
podSelector:
matchLabels:
app: [SERVICE_NAME]
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: [ALLOWED_CONSUMER]
ports:
- port: [PORT]
protocol: TCP
egress:
- to:
- podSelector:
matchLabels:
app: [ALLOWED_DEPENDENCY]
ports:
- port: [PORT]
protocol: TCP
- to: # Allow DNS
- namespaceSelector: {}
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- port: 53
protocol: UDP
```
**Docker Compose network isolation:**
- Create dedicated networks for each service tier (frontend, backend, database)
- Never use `network_mode: host`
- Restrict inter-service communication to only required paths
- Disable ICC (inter-container communication) on default bridge network
### Supply Chain Security
**Image Signing and Verification:**
- Sign all production images with [SIGNING TOOL: Cosign / Notary / Docker Content Trust]
- Verify signatures at deployment using [ADMISSION CONTROLLER: Kyverno / OPA Gatekeeper / Connaisseur]
- Maintain a transparency log of all signed artifacts
- SBOM (Software Bill of Materials) generation for every image using [TOOL: Syft / Trivy / Docker SBOM]
**Registry Security:**
- Enable [REGISTRY] vulnerability scanning with automatic blocking of critical CVEs
- Implement image promotion pipeline: dev → staging → production registries
- Tag immutability: prevent overwriting existing tags in production registry
- Regular cleanup of untagged and unused images (retention policy: [DAYS])
- Access control: CI/CD has push access, production clusters have pull-only access
### Secrets in Containers
- NEVER embed secrets in images or pass via environment variables for [HIGH SENSITIVITY] data
- Use [SECRET SOLUTION: Kubernetes Secrets with encryption at rest / Vault Agent sidecar / AWS Secrets Manager CSI driver / sealed-secrets]
- Mount secrets as files, not environment variables (prevents leakage via /proc, debugging tools, crash dumps)
- Rotate secrets without container restart using [METHOD: Vault Agent / CSI driver rotation / sidecar watch]
### Monitoring and Incident Response
- Runtime threat detection with [TOOL: Falco / Sysdig / Aqua / Prisma Cloud]
- Alert on: shell execution in container, unexpected network connections, file writes to read-only filesystem, privilege escalation attempts, crypto mining indicators
- Container forensics: Enable audit logging for container lifecycle events
- Incident runbook: Steps for isolating, investigating, and remediating a compromised container
- Regular penetration testing of container infrastructure on [SCHEDULE: quarterly / monthly]Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[APPLICATION NAME][NUMBER][IMAGE][DIGEST][SERVICE NAME][BUILD_IMAGE][DEPENDENCY_FILES][INSTALL_DEPENDENCIES][BUILD_COMMAND][MINIMAL_BASE_IMAGE][BUILD_OUTPUT][HEALTH_CHECK_COMMAND][PORT][BINARY][UID][GID][ONLY_IF_ABSOLUTELY_NEEDED][REQUEST_MEMORY][REQUEST_CPU][LIMIT_MEMORY][LIMIT_CPU][STORAGE_LIMIT][CACHE_DIR][SIZE][NAMESPACE][SERVICE_NAME][ALLOWED_CONSUMER][ALLOWED_DEPENDENCY][REGISTRY][DAYS][HIGH SENSITIVITY]