Kubernetes cookbook · Intermediate
Write a production-ready Deployment
Start new services from a Deployment that has the probes, resources and security settings production needs.
Approach
Combine pinned images, requests and a memory limit, readiness/liveness/startup probes, a restricted security context, graceful termination and a dedicated service account in one template.
Solution
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
labels: {app.kubernetes.io/name: api}
spec:
replicas: 3
selector:
matchLabels: {app.kubernetes.io/name: api}
strategy:
rollingUpdate: {maxUnavailable: 0, maxSurge: 1}
template:
metadata:
labels: {app.kubernetes.io/name: api}
spec:
serviceAccountName: api
automountServiceAccountToken: false
terminationGracePeriodSeconds: 45
securityContext:
runAsNonRoot: true
seccompProfile: {type: RuntimeDefault}
containers:
- name: api
image: ghcr.io/acme/api:1.4.2
ports: [{name: http, containerPort: 8080}]
resources:
requests: {cpu: 200m, memory: 256Mi}
limits: {memory: 512Mi}
startupProbe:
httpGet: {path: /ready, port: http}
failureThreshold: 30
periodSeconds: 2
readinessProbe:
httpGet: {path: /ready, port: http}
periodSeconds: 5
livenessProbe:
httpGet: {path: /live, port: http}
periodSeconds: 10
lifecycle:
preStop: {sleep: {seconds: 5}}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
volumeMounts: [{name: tmp, mountPath: /tmp}]
volumes: [{name: tmp, emptyDir: {}}]
Pitfalls
- Liveness probes that check dependencies, restarting healthy pods during a database blip.
- CPU limits on latency-sensitive services (throttling); set requests instead.
- A
replicasfield together with an HPA.
Variations
- Add a PodDisruptionBudget and topology spread constraints (see those recipes).
- Package as a Helm chart or Kustomize base for reuse.
Further reading: Configuration best practices
Reference: https://kubernetes.io/docs/concepts/configuration/overview/
More Kubernetes recipes
- Autoscale a Deployment on CPU and memory
- Debug a distroless pod with an ephemeral container
- Default-deny network policies that keep DNS working
- Enforce the restricted Pod Security Standard
- Expose a service over HTTPS with automatic certificates
- Give a CI pipeline least-privilege deploy access
- Handle SIGTERM in your application for Kubernetes
- Manage dev, staging and prod with Kustomize overlays