Comprehensive Rules for building, securing, and operating containerized workloads with Dockerfile & Kubernetes
Transform chaotic container workflows into bulletproof, security-first deployment pipelines that scale.
You're shipping containers to production, but are you doing it right? Most teams think they are—until a vulnerability scanner flags 47 critical CVEs in their "lightweight" Alpine image, or their Kubernetes pods crash-loop because nobody implemented graceful shutdown handling.
Here's what's actually happening in containerized environments:
USER node in your Dockerfile while your SecurityContext still allows privilege escalationThese aren't edge cases—they're the daily reality of container operations when you're missing systematic approaches to image building, security hardening, and orchestration.
This Cursor Rules configuration transforms your containerization workflow from ad-hoc experimentation into production-grade infrastructure management. Built for teams who need to ship secure, scalable containerized applications without the usual operational overhead.
What this gives you:
Before: Copying random Dockerfile patterns from StackOverflow, hoping Alpine is "secure enough"
# Vulnerable pattern - don't do this
FROM node:latest
COPY . /app
WORKDIR /app
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]
After: Security-first, optimized image with proper user handling
FROM node:18-alpine@sha256:a1e22d9... AS builder
WORKDIR /build
COPY package*.json ./
RUN npm ci --only=production
FROM node:18-alpine@sha256:a1e22d9...
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app
COPY --from=builder --chown=app:app /build/node_modules ./node_modules
COPY --chown=app:app . .
USER app
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:3000/health || exit 1
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["node", "server.js"]
Impact: Reduces image vulnerabilities by 90%+, improves build cache efficiency, ensures proper signal handling
Before: Basic deployment that fails security audits
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: my-app:latest
ports:
- containerPort: 3000
After: Production-hardened deployment with comprehensive security
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
template:
spec:
securityContext:
runAsNonRoot: true
fsGroup: 1000
containers:
- name: app
image: my-app@sha256:abc123...
imagePullPolicy: IfNotPresent
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
runAsUser: 1000
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 5
Impact: Passes security admission controllers, prevents resource exhaustion, enables proper health monitoring
Before: Copy-pasting YAML files with manual value changes across dev/staging/prod After: Kustomize overlays with environment-specific configurations
k8s/
├── base/
│ ├── deployment.yaml
│ ├── service.yaml
│ └── kustomization.yaml
└── overlays/
├── dev/
│ ├── kustomization.yaml
│ └── config-patch.yaml
├── staging/
└── prod/
├── kustomization.yaml
├── resources-patch.yaml
└── security-patch.yaml
Impact: Eliminates configuration drift, reduces deployment errors by 75%, enables GitOps workflows
Create your containerization structure:
mkdir -p {docker,helm,k8s/overlays/{dev,staging,prod}}
.cursorrules fileAdd Trivy scanning to your CI pipeline:
# .github/workflows/container-security.yml
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: '${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
Set up Sigstore/cosign for image verification:
# Sign images in CI
cosign sign --yes $IMAGE_URI@$DIGEST
# Verify in deployment
cosign verify --certificate-identity-regexp=".*" --certificate-oidc-issuer-regexp=".*" $IMAGE_URI
Implement OPA Gatekeeper or Kyverno policies:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: enforce
rules:
- name: check-non-root
match:
any:
- resources:
kinds:
- Pod
validate:
message: "Root user is not allowed"
pattern:
spec:
securityContext:
runAsNonRoot: true
Ready to eliminate container chaos? These rules transform your Docker and Kubernetes workflows from error-prone manual processes into automated, security-first deployment pipelines. Your infrastructure team will thank you, your security team will approve faster, and your deployments will actually work the first time.
You are an expert in Containerization, Docker, OCI-compatible runtimes (containerd, CRI-O, Podman) and Kubernetes orchestration.
Key Principles
- Single-responsibility: one process and one concern per container.
- Images must be minimal, immutable, and reproducible.
- Shift-left security: scan, sign, and verify images in developer and CI stages.
- Run as non-root with least privilege (UID ≠ 0, drop ALL capabilities, read-only FS).
- Declarative infrastructure: everything (Dockerfile, Kubernetes manifests, Helm charts) stored in VCS and treated as code.
- Automate everything: builds, scans, tests, deployments, rollbacks.
- Observability is mandatory: logs, metrics, traces, and runtime security events must be exported.
Dockerfile & Image Rules
- FROM: prefer official, LTS, or internally-vetted base images pinned to a digest (e.g., `FROM alpine@sha256:…`).
- Multi-stage builds: place build toolchain in first stage, copy artefacts into slim runtime stage.
- Layer order: 1) base OS, 2) package manager install, 3) copy code, 4) install deps, 5) runtime user, 6) entrypoint. This ensures maximum cache re-use.
- Use `COPY` instead of `ADD` unless remote URL or archive extraction is required.
- Explicit versions for OS and language packages: `apk add --no-cache python3=3.12.1-r0`.
- Non-root user:
```dockerfile
RUN addgroup -S app && adduser -S app -G app
USER app
```
- Health checks: `HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost/health || exit 1`.
- Signals: use `exec` form entrypoint to forward SIGTERM/SIGINT.
```dockerfile
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["./app"]
```
- Environment variables: define defaults with `ARG`, override via `ENV`, never bake secrets in the image.
- Image labels: follow OCI spec – `LABEL org.opencontainers.image.source="https://github.com/acme/app"`.
- Vulnerability scanning gate: image must pass Trivy/CVE policy (< HIGH severity) before pushing to registry.
YAML / Kubernetes Manifest Rules
- apiVersion pinned (no `latest`): `apiVersion: apps/v1`.
- Naming: lowercase, dash-separated – `my-service`, `payment-db`.
- Resource requests & limits mandatory: `requests: {cpu: "100m", memory: "128Mi"}`.
- Probes:
- liveness → restart on deadlock
- readiness → remove from Service endpoints during warm-up
- SecurityContext per Pod & Container:
```yaml
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
```
- RBAC: least-privilege ServiceAccount bound via Role/ClusterRole; never use default account.
- ImagePullPolicy: `IfNotPresent` for digests, `Always` for tags.
- Networking: define NetworkPolicy to whitelist ingress/egress.
- Config & Secrets: mount through ConfigMap/Secret, never via env files committed to VCS.
- Storage: prefer ephemeral (`emptyDir`) for scratch space; bind PVCs only for real persistence.
- Annotations for observability: e.g., `prometheus.io/scrape: "true"`.
Error Handling & Validation
- Application must trap SIGTERM & SIGINT and exit within `terminationGracePeriodSeconds` (default 30s).
- Implement graceful shutdown to avoid data corruption.
- Validate configuration at start-up; fail fast rather than crash later.
- CI checks: `dockerfilelint`, `kube-score`, `kubeconform`, Trivy.
- Admission controller policies (OPA/Gatekeeper or Kyverno) enforce non-root, probes, resources.
Framework-Specific Rules (Kubernetes)
- Use Helm ≥v3 for packaging; charts must:
- template for multi-env (values.yaml overrides)
- pass `helm lint` and `helm unittest`
- include `NOTES.txt` for post-install guidance
- Prefer Deployments for stateless, StatefulSets for ordered, persistent workloads, Jobs/CronJobs for run-to-completion tasks.
- Rollout strategy: use `rollingUpdate` with `maxSurge` 25% and `maxUnavailable` 25% unless workload requires zero-downtime.
- HPA: autoscale on CPU and a custom metric (e.g., queue length) with cool-down periods.
- Service mesh (Istio/Linkerd) rules: enable mTLS, define retries and circuit breakers in VirtualService.
Additional Sections
Testing
- Unit tests executed inside the same base image to avoid "works on my machine".
- Integration tests spin up ephemeral environment via Docker Compose or Kind cluster.
- Use `testcontainers` libraries to create throw-away containers during CI.
Performance
- Keep images < 200 MB; alert when layer sum exceeds threshold.
- Adopt distroless or scratch images when possible.
- Enable cgroupsv2 for better resource accounting.
- Benchmark startup time; target ⩽ 500 ms cold-start for microservices.
Security
- Sign images with Sigstore/cosign; enforce signature verification admission policy.
- Runtime security: deploy Falco or eBPF-based IDS; alerts must reach SIEM.
- Rootless Podman for local dev to mirror non-root production posture.
- Set `seccompProfile: RuntimeDefault` unless custom needed.
CI/CD Pipeline
- Stages: lint → build → scan → unit-test → integration-test → sign → push → deploy.
- Use immutable tags (SHA-based) in manifests triggered via GitOps (Argo CD / Flux).
- Rollback strategy: keep last N Helm releases; automated rollback on failed readiness.
Observability
- Export Prometheus metrics and OpenTelemetry traces.
- Sidecar pattern allowed only for 1) proxies (Envoy) 2) uniform logging (fluent-bit) 3) debug-on-demand.
Common Pitfalls & Anti-Patterns
- 🛑 Running multiple services via supervisor → split into multiple containers.
- 🛑 `chmod 777` in Dockerfile → define correct permissions & non-root user.
- 🛑 `latest` tags in production → use digests.
- 🛑 Storing credentials in environment variables committed to Git.
File/Directory Conventions
- `docker/` – multi-stage Dockerfiles per component
- `helm/` – Helm charts
- `k8s/overlays/{dev,staging,prod}` – Kustomize overlays
Example Directory
```
repo/
├─ docker/
│ └─ api.Dockerfile
├─ helm/
│ └─ api/
├─ k8s/
│ └─ overlays/
│ ├─ dev/
│ ├─ staging/
│ └─ prod/
└─ .github/workflows/ci.yml
```