Kubernetes YAML Cheat Sheet

High-value Kubernetes YAML patterns for Pods, Deployments, Services, probes, resources, scheduling, and day-to-day manifest authoring.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Manifest Basics
Minimal Pod manifest
apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
  labels:
    app: demo
spec:
  containers:
    - name: app
      image: nginx:1.27
      ports:
        - containerPort: 80

# Smallest practical Pod YAML shape.

Multiple resources in one YAML file
apiVersion: v1
kind: Namespace
metadata:
  name: demo

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: demo
data:
  APP_ENV: production

# Separate resources with `---`.

Apply YAML file
kubectl apply -f app.yaml

# Create or update resources from a YAML file.

Apply YAML directory
kubectl apply -f k8s/

# Apply all manifests in a directory.

Preview manifest changes
kubectl diff -f app.yaml

# See what apply would change.

## Metadata, Labels, and Annotations
Labels and annotations example
metadata:
  name: api
  namespace: prod
  labels:
    app.kubernetes.io/name: api
    app.kubernetes.io/component: backend
    app.kubernetes.io/part-of: storefront
    tier: web
  annotations:
    kubectl.kubernetes.io/default-container: api
    reloader.stakater.com/auto: "true"

# Common metadata block for selectors and tooling.

Get resources by label selector
kubectl get pods -l app.kubernetes.io/name=api

# Use labels to query related objects.

Add or update label from CLI
kubectl label deployment api tier=web --overwrite

# Patch a label onto a resource.

Add annotation from CLI
kubectl annotate deployment api owner=platform-team --overwrite

# Write metadata without affecting selectors.

## Pods and Containers
Override container command and args
apiVersion: v1
kind: Pod
metadata:
  name: args-demo
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c"]
      args: ["echo hello && sleep 3600"]

# Set entrypoint-style command in YAML.

Set explicit environment variables
env:
  - name: APP_ENV
    value: production
  - name: LOG_LEVEL
    value: info

# Define environment variables with `env`.

Load env from ConfigMap and Secret
envFrom:
  - configMapRef:
      name: app-config
  - secretRef:
      name: app-secrets

# Import environment values into a container.

Expose named container ports
ports:
  - name: http
    containerPort: 8080
  - name: metrics
    containerPort: 9090

# Name ports for Service targeting and probes.

Use imagePullSecrets
spec:
  imagePullSecrets:
    - name: regcred
  containers:
    - name: app
      image: registry.example.com/app:1.2.3

# Authenticate to a private registry.

## Deployments
Basic Deployment YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: ghcr.io/example/api:1.0.0
          ports:
            - containerPort: 8080

# Run a replicated stateless workload.

Customize rolling update strategy
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxUnavailable: 1
    maxSurge: 1

# Tune availability during rollout.

Set deployment progress deadline
progressDeadlineSeconds: 600
minReadySeconds: 10
revisionHistoryLimit: 5

# Mark failed rollouts sooner.

Apply deployment manifest
kubectl apply -f deployment.yaml

# Create or update the Deployment.

Watch rollout status
kubectl rollout status deployment/api

# See whether the new ReplicaSet becomes ready.

## Probes and Resources
HTTP liveness, readiness, and startup probes
livenessProbe:
  httpGet:
    path: /healthz
    port: http
  initialDelaySeconds: 10
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /ready
    port: http
  initialDelaySeconds: 5
  periodSeconds: 5

startupProbe:
  httpGet:
    path: /startup
    port: http
  failureThreshold: 30
  periodSeconds: 10

# Use health checks to control traffic and restarts.

CPU and memory requests/limits
resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
  limits:
    cpu: "500m"
    memory: "512Mi"

# Define scheduler reservations and hard caps.

Container securityContext
securityContext:
  runAsNonRoot: true
  runAsUser: 10001
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]

# Drop privileges and run as non-root.

## Scheduling and Placement
Schedule onto labeled nodes
nodeSelector:
  node.kubernetes.io/instance-type: c6i.large

# Require a simple node label match.

Use required node affinity
affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: topology.kubernetes.io/zone
              operator: In
              values: ["us-west1-a", "us-west1-b"]

# More expressive scheduling constraints.

Spread replicas across nodes
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: api
          topologyKey: kubernetes.io/hostname

# Avoid colocating the same app on one node.

Tolerate tainted nodes
tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "batch"
    effect: "NoSchedule"

# Allow pods onto special-purpose nodes.

## YAML Validation and Troubleshooting
Server-side dry run
kubectl apply --dry-run=server -f deployment.yaml -o yaml

# Validate a manifest against the API server without persisting it.

Explain a field path
kubectl explain deployment.spec.template.spec.containers

# Discover valid YAML fields from kubectl.

Show last-applied configuration
kubectl apply view-last-applied deployment/api

# Inspect the apply annotation on a live resource.

Recommended next

No recommendations yet.