Kubernetes cookbook · Intermediate

Write a production-ready Deployment

Start new services from a Deployment that has the probes, resources and security settings production needs.

Create a free account to save this page, take notes and track your progress. Sign in

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 replicas field 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

Was this page helpful?