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

Structure every object with apiVersion, kind, metadata, and spec.

Minimal Pod manifest

Smallest practical Pod YAML shape.

yamlANYbasicspodmanifest
yaml
apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
  labels:
    app: demo
spec:
  containers:
    - name: app
      image: nginx:1.27
      ports:
        - containerPort: 80

A Kubernetes object is typically expressed as YAML with `apiVersion`, `kind`, `metadata`, and `spec`. Pods are usually used directly only for debugging or one-off workloads; Deployments are better for managed application Pods.

Multiple resources in one YAML file

Separate resources with `---`.

yamlANYbasicsmulti-document
yaml
apiVersion: v1
kind: Namespace
metadata:
  name: demo

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

Grouping related objects into one manifest is convenient for app-level deployment and review.

Apply YAML file

Create or update resources from a YAML file.

bashANYkubectlapplyyaml
bash
kubectl apply -f app.yaml

`kubectl apply` accepts YAML or JSON and creates the resource if it does not exist yet. `kubectl diff -f ...` is useful before applying changes.

Apply YAML directory

Apply all manifests in a directory.

bashANYkubectlapplydirectory
bash
kubectl apply -f k8s/

A common declarative workflow is to keep configuration files in a directory and apply them together.

Preview manifest changes

See what apply would change.

bashANYkubectldiffreview
bash
kubectl diff -f app.yaml

Use this before apply in CI or during review-heavy workflows.

Metadata, Labels, and Annotations

Use labels for selection and annotations for non-identifying metadata.

Labels and annotations example

Common metadata block for selectors and tooling.

yamlANYmetadatalabelsannotations
yaml
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"

Labels are queryable and support selectors; annotations hold arbitrary metadata that tools and operators consume.

Get resources by label selector

Use labels to query related objects.

bashANYlabelsselectorskubectl
bash
kubectl get pods -l app.kubernetes.io/name=api

Add or update label from CLI

Patch a label onto a resource.

bashANYlabelskubectl
bash
kubectl label deployment api tier=web --overwrite

Add annotation from CLI

Write metadata without affecting selectors.

bashANYannotationskubectl
bash
kubectl annotate deployment api owner=platform-team --overwrite

Pods and Containers

Container command, args, env, mounts, and restart behavior.

Override container command and args

Set entrypoint-style command in YAML.

yamlANYpodcontainercommandargs
yaml
apiVersion: v1
kind: Pod
metadata:
  name: args-demo
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c"]
      args: ["echo hello && sleep 3600"]

Use `command` and `args` to define commands and arguments for a container in a Pod spec.

Set explicit environment variables

Define environment variables with `env`.

yamlANYenvcontainer
yaml
env:
  - name: APP_ENV
    value: production
  - name: LOG_LEVEL
    value: info

Use `env` for individual variables; use `envFrom` when importing all keys from a ConfigMap or Secret.

Load env from ConfigMap and Secret

Import environment values into a container.

yamlANYenvconfigmapsecret
yaml
envFrom:
  - configMapRef:
      name: app-config
  - secretRef:
      name: app-secrets

`envFrom` is concise for app-style configuration but can make exact variable origins less explicit than `env`.

Expose named container ports

Name ports for Service targeting and probes.

yamlANYportscontainer
yaml
ports:
  - name: http
    containerPort: 8080
  - name: metrics
    containerPort: 9090

Use imagePullSecrets

Authenticate to a private registry.

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

Deployments

Declarative rolling workloads for stateless applications.

Basic Deployment YAML

Run a replicated stateless workload.

yamlANYdeploymentworkload
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

Deployments manage ReplicaSets and provide declarative rollout behavior for Pods.

Customize rolling update strategy

Tune availability during rollout.

yamlANYdeploymentrollingupdate
yaml
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxUnavailable: 1
    maxSurge: 1

Set deployment progress deadline

Mark failed rollouts sooner.

yamlANYdeploymentrollout
yaml
progressDeadlineSeconds: 600
minReadySeconds: 10
revisionHistoryLimit: 5

Apply deployment manifest

Create or update the Deployment.

bashANYdeploymentapply
bash
kubectl apply -f deployment.yaml

Watch rollout status

See whether the new ReplicaSet becomes ready.

bashANYdeploymentrollout
bash
kubectl rollout status deployment/api

Probes and Resources

Health checks and resource management fields.

HTTP liveness, readiness, and startup probes

Use health checks to control traffic and restarts.

yamlANYprobeshealth
yaml
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

CPU and memory requests/limits

Define scheduler reservations and hard caps.

yamlANYresourcescpumemory
yaml
resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
  limits:
    cpu: "500m"
    memory: "512Mi"

Requests influence scheduling; limits constrain runtime resource use.

Container securityContext

Drop privileges and run as non-root.

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

Scheduling and Placement

Node selectors, affinity, tolerations, and topology spread.

Schedule onto labeled nodes

Require a simple node label match.

yamlANYschedulingnodeSelector
yaml
nodeSelector:
  node.kubernetes.io/instance-type: c6i.large

Use required node affinity

More expressive scheduling constraints.

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

Spread replicas across nodes

Avoid colocating the same app on one node.

yamlANYaffinityanti-affinityha
yaml
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: api
          topologyKey: kubernetes.io/hostname

Tolerate tainted nodes

Allow pods onto special-purpose nodes.

yamlANYtaintstolerations
yaml
tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "batch"
    effect: "NoSchedule"

YAML Validation and Troubleshooting

Check generated manifests before deploying.

Server-side dry run

Validate a manifest against the API server without persisting it.

bashANYvalidationdry-runserver
bash
kubectl apply --dry-run=server -f deployment.yaml -o yaml

Great for CI and schema validation when the cluster has the CRDs and admission rules you care about.

Explain a field path

Discover valid YAML fields from kubectl.

bashANYkubectlexplainschema
bash
kubectl explain deployment.spec.template.spec.containers

Show last-applied configuration

Inspect the apply annotation on a live resource.

bashANYapplydebugging
bash
kubectl apply view-last-applied deployment/api

Recommended next

No recommendations yet.