Kubernetes Deployment YAML Tutorial

Kubernetes Deployment YAML Tutorial

Introduction

A Deployment is the Kubernetes object most beginners meet first and the one they will use for the rest of their careers. It is how a web application actually runs on a cluster: you describe the application you want — the image, how many copies, which port it listens on — and the Deployment makes it so, keeps it so, and updates it safely when you change your mind.

This tutorial is a complete, working example. You will write a Deployment and a Service for a small web application, understand every field in both files, apply them with kubectl, watch the rollout, update the image, and roll back when an update goes wrong. Every YAML block here is complete and valid — copy it as written and it will work on any cluster. You need a running cluster and the basics from our Kubernetes Tutorial for Beginners: what a Pod is, how kubectl talks to the cluster, and how to check that your cluster is up. A local cluster from minikube or kind is enough for everything in this tutorial.

Version note (28 Nov 2026): the current Kubernetes is 1.37 “Garhwal”, released 26 August 2026, with the latest patch 1.37.3 (25 November 2026). Kubernetes 1.38 is planned for around 16 December 2026. The Deployment API used here — apps/v1 — has been stable since Kubernetes 1.9, so the YAML in this tutorial works unchanged on every supported version. Re-check the current patch before publishing, as patch releases arrive monthly.

What a Deployment Is — and Why Not Bare Pods

A Pod is the smallest thing Kubernetes runs: one or more containers that share a network and storage. You can create a Pod directly with kubectl, and for a quick experiment that is fine. For anything real, it is not enough, because a bare Pod has no self-healing and no update story. If the node it runs on dies, the Pod is gone. If you want a new version of the image, you delete the Pod and create a new one by hand, with downtime in between.

A Deployment fixes both problems by owning a ReplicaSet, which in turn owns the Pods. The ReplicaSet’s job is simple: keep the right number of Pods running. If a Pod crashes, the ReplicaSet starts a replacement. If you ask for three replicas and only two are running, it creates a third. The Deployment’s job sits above that: it manages the ReplicaSets. When you change the Pod template — a new image, a new environment variable — the Deployment creates a new ReplicaSet, scales it up gradually, and scales the old one down. That gradual swap is a rolling update, and it is the reason deployments usually happen with no downtime.

The chain is worth memorising, because it explains almost every Deployment behaviour you will meet: Deployment → ReplicaSet → Pod. You edit the Deployment; the Deployment creates a ReplicaSet; the ReplicaSet creates the Pods. You almost never touch a ReplicaSet or a Pod directly — if you do, the Deployment will undo your change on the next reconciliation, because the desired state is the Deployment’s spec, not the live object.

A Deployment also keeps history. By default it retains the last 10 old ReplicaSets, which is what makes rollback possible: rolling back means scaling an old ReplicaSet back up. That limit is configurable, and the section on rolling back explains how. If you are packaging applications for reuse rather than writing raw YAML, Helm does this same work with templates — our Helm Tutorial for Beginners covers that next step — and if you are studying for the CKA exam, Deployments are one of the most-tested objects in it, covered in our CKA Certification Guide 2026.

The Complete Deployment YAML, Field by Field

Here is the whole Deployment. Read it top to bottom first, then the field-by-field explanation below it.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
spec:
  replicas: 3
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
        - name: web
          image: nginx:1.27
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: "250m"
              memory: "128Mi"
            limits:
              cpu: "500m"
              memory: "256Mi"
          readinessProbe:
            httpGet:
              path: /
              port: 80
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /
              port: 80
            initialDelaySeconds: 15
            periodSeconds: 20
  • `apiVersion: apps/v1` is the API group and version for Deployments. apps/v1 is the stable version — older tutorials use extensions/v1beta1 or apps/v1beta2, both long removed. If you copy YAML from an old blog post and kubectl complains about the apiVersion, this is almost always why.
  • `kind: Deployment` says what kind of object this is. The apiVersion and kind together tell the API server which schema to validate against.
  • `metadata.name: web-app` is the Deployment’s name. It must be unique in its namespace, and it becomes the prefix for the ReplicaSet and Pod names.
  • `metadata.labels` are key-value tags attached to the Deployment itself. Labels are how Kubernetes objects find each other, and the ones here are for your own organisation — kubectl get deployments -l app=web-app selects Deployments carrying this label.
  • `spec.replicas: 3` is the desired number of Pods. The ReplicaSet will keep three running. Change this number and apply the file again, and Kubernetes scales up or down to match.
  • `spec.revisionHistoryLimit: 10` is how many old ReplicaSets to keep for rollback. Ten is also the default, so this line only makes the default explicit — it is included here so you know where to change it. Setting it to 0 disables rollback entirely, which you should never do in production.
  • `spec.selector.matchLabels` is the most important field in the file, and the most commonly broken. It tells the Deployment which Pods belong to it. The Deployment finds its Pods by matching these labels against the labels on the Pod template — not by name. If the selector and the template labels do not match, kubectl apply fails with an error, and that is a good thing: a Deployment that cannot find its own Pods would be far worse.
  • `spec.template` is the Pod template: the blueprint for every Pod this Deployment creates. Everything inside it is a Pod spec. Change anything in the template and the Deployment treats it as a new version and starts a rollout.
  • `template.metadata.labels` are the labels stamped onto every Pod. These must include the labels in spec.selector.matchLabels — app: web-app here. The selector-template match is the single most common Deployment mistake, and there is a whole section on it below.
  • `spec.containers` is the list of containers in each Pod. A Pod can run several containers, but one is the normal case for a web application.
  • `containers[].name: web` is the container’s name within the Pod. It is how you refer to this container in commands like kubectl logs deployment/web-app -c web and in kubectl set image.
  • `containers[].image: nginx:1.27` is the container image and tag. Always use a specific tag, never latest: latest moves, so two Pods created at different times can run different code, and a rollout cannot tell whether the image changed. Pin the version.
  • `containers[].ports[].containerPort: 80` declares the port the container listens on. It is informational — Kubernetes does not enforce it — but it documents the contract and is used by tooling and by the Service in the next section.
  • `resources.requests` is what the container is guaranteed: 250 millicores of CPU and 128 MiB of memory. The scheduler uses requests to decide which node the Pod fits on. `resources.limits` is the ceiling: 500 millicores and 256 MiB. Exceed the memory limit and the container is killed; exceed the CPU limit and it is throttled. Set requests to what the application actually uses, not to zero — a Pod with no requests can be scheduled onto a node that has no room for it.
  • `readinessProbe` asks whether the container is ready to receive traffic. This one makes an HTTP GET to / on port 80, starting 5 seconds after the container starts and repeating every 10 seconds. A Pod that fails its readiness probe is removed from the Service’s endpoints — it keeps running, but no traffic reaches it — which is how a slow-starting application avoids receiving requests before it can answer them.
  • `livenessProbe` asks whether the container is still alive. Same HTTP check, starting after 15 seconds and repeating every 20 seconds. If it fails, Kubernetes restarts the container. The difference matters: readiness controls traffic, liveness controls restarts. A probe that is too aggressive on liveness will restart a healthy container that was merely slow; a missing liveness probe lets a deadlocked process run forever.

Save this file as deployment.yaml. The next section adds the Service, and then you will apply both.

The Service: Exposing Your Pods

A Deployment keeps Pods running, but Pods are ephemeral — their IP addresses change when they are replaced. A Service gives them a stable address: a single IP and DNS name that always routes to the current, healthy Pods. Without a Service, nothing else in the cluster can reliably reach your application.

apiVersion: v1
kind: Service
metadata:
  name: web-app
spec:
  selector:
    app: web-app
  ports:
    - port: 80
      targetPort: 80
  type: ClusterIP
  • `apiVersion: v1` — Services are core objects, so they use the core API version, not apps/v1.
  • `spec.selector.app: web-app` is how the Service finds the Pods: it selects every Pod carrying the label app: web-app, which is exactly the label the Deployment stamps on its Pods. This is the second place the label matters — the Deployment’s selector, the Pod template’s labels and the Service’s selector must all agree on the same label.
  • `ports[].port: 80` is the port the Service listens on. `targetPort: 80` is the port on the Pod it forwards to. They are often the same number, but they do not have to be — the Service can listen on 80 and forward to a container listening on 8080.
  • `type: ClusterIP` is the default Service type: the Service gets an IP reachable only from inside the cluster. That is the right default — most applications are reached by other things inside the cluster, not directly from the internet.

The other two types you will meet:

  • NodePort opens the same port on every node, in the range 30000–32767, so the application is reachable at <node-ip>:<node-port> from outside the cluster. Change type to NodePort and add a nodePort to reach it from your laptop on a local cluster:
  type: NodePort
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30080
  • LoadBalancer asks your cloud provider to provision an external load balancer and give the Service a public IP. It is the standard choice on a managed cloud cluster — EKS, GKE or AKS — and it does nothing useful on a local cluster, where there is no cloud provider to provision anything. Use NodePort or port-forwarding locally instead.

Save this file as service.yaml. You now have everything the application needs.

Applying It and Watching It Run

Apply both files, then watch what Kubernetes does:

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

kubectl apply is declarative: it sends the desired state to the API server, which creates the objects if they do not exist and updates them if they do. Running the same command twice changes nothing the second time, which is why apply — not create — is the command to use for files you keep in Git.

Check the rollout:

kubectl get deployments
kubectl get pods -l app=web-app
kubectl get service web-app

kubectl get deployments shows the Deployment with its desired, current and up-to-date replica counts. kubectl get pods -l app=web-app lists the three Pods, selected by the same label the Service uses. Wait until all three show Running and 1/1 in the READY column — the 1/1 means the readiness probe is passing. kubectl get service web-app shows the ClusterIP.

Now confirm the rollout finished cleanly:

kubectl rollout status deployment/web-app

This command blocks until the rollout completes or fails, and prints successfully rolled out when it does. It is the command to run in a script or a pipeline after every kubectl apply — it turns “I sent the YAML” into “the new version is actually running”.

Two more commands complete the picture. kubectl describe deployment web-app shows the Deployment’s events, including any errors from the last rollout — it is the first place to look when a rollout stalls. And to actually see the application working, forward a local port to the Service:

kubectl port-forward service/web-app 8080:80

Open http://localhost:8080 in a browser and you should see the nginx welcome page. Stop the port-forward with Ctrl+C when you are done.

Updating the Image: Rollouts

Updating a Deployment means changing the Pod template, and the most common change is a new image version. There are two ways to do it: edit the YAML file and re-apply, or use kubectl set image, which edits the live object:

kubectl set image deployment/web-app web=nginx:1.28

The arguments are the Deployment, the container name from the YAML (web), and the new image. Either way, the Deployment creates a new ReplicaSet with the new image and starts a rolling update: it scales the new ReplicaSet up and the old one down, following the default rolling update strategy. The defaults are maxSurge: 25% and maxUnavailable: 25% — during the update, Kubernetes may create up to 25% more Pods than the desired count, and may have up to 25% of Pods unavailable. With three replicas, that means it creates one new Pod, waits for it to become ready, then removes one old Pod, and repeats until all three are new. At no point is the application fully down.

Watch it happen:

kubectl rollout status deployment/web-app
kubectl get pods -l app=web-app -w

The -w flag watches the Pod list live, so you can see old Pods terminating and new ones starting. If the new image is broken — a typo in the tag, an image that does not exist — the new Pods never become ready, the rollout stalls, and kubectl rollout status eventually reports that the progress deadline was exceeded. The default deadline is 600 seconds. The old Pods keep serving traffic throughout, which is exactly why the rolling update exists: a bad image is an inconvenience, not an outage. Fix the image and re-apply, and the rollout proceeds.

To see what each revision was, look at the history:

kubectl rollout history deployment/web-app

The output lists revisions and their change-cause, if one was recorded. Recording a change-cause is worth doing in real systems — annotate the Deployment when you deploy, and the history tells you which release each revision was:

kubectl annotate deployment/web-app kubernetes.io/change-cause="nginx 1.28 upgrade"

Rolling Back

When a release is bad and fixing forward will take too long, roll back. Kubernetes keeps the old ReplicaSets specifically for this:

kubectl rollout undo deployment/web-app

This restores the Pod template from the previous revision — the old ReplicaSet scales back up, the new one scales down, using the same rolling update settings. It is itself a new rollout, so watch it the same way:

kubectl rollout status deployment/web-app

To roll back to a specific revision rather than the previous one, list the history first, then name the revision:

kubectl rollout history deployment/web-app
kubectl rollout undo deployment/web-app --to-revision=1

Three things about rollback are worth knowing before you need it. First, a rollback is a new revision, not a rewind: the revision numbers keep climbing, and the restored template becomes the latest revision. Second, rollback only restores the Pod template — it does not undo changes to ConfigMaps or Secrets, and it does not reverse a database migration. If the bad release changed the database schema, rolling back the Pods can leave the old code running against a new schema. Third, rollback is limited by `revisionHistoryLimit`: with the default of 10, you can go back ten revisions. Set it too low and the revision you need may already have been pruned. And one warning that catches GitOps users: if your Deployment is managed by Helm or Argo CD, a kubectl rollout undo makes the cluster disagree with the source of truth, and the next sync will put the bad version back. Undo is an emergency step — then fix the source, whether that is the YAML in Git or the Helm values, so the rollback sticks. Our Helm Tutorial for Beginners explains how Helm’s own rollback works for Helm-managed releases.

Common YAML Mistakes

Most Deployment failures are YAML mistakes, and most of them are one of these five.

  • Selector and template labels do not match. The Deployment’s spec.selector.matchLabels must match the labels in spec.template.metadata.labels. If they differ — app: web-app in one and app: webapp in the other — kubectl apply fails with an error about the selector not matching the template. This is the single most common Deployment error. Copy the label from one place to the other; do not retype it.
  • Indentation is wrong. YAML is whitespace-sensitive, and two spaces is the convention. A field indented one level too deep becomes a child of the wrong key; a field indented one level too shallow becomes a sibling of something it does not belong to. Tabs are not allowed at all — a tab anywhere in the file is an error. If kubectl reports a field it does not recognise, check the indentation of the lines above it first.
  • The Service selector does not match the Pod labels. The Deployment is healthy, the Pods are running, but the Service has no endpoints and nothing can reach the application. Run kubectl get endpoints web-app: if the list is empty, the Service’s selector is not matching any Pod. Compare spec.selector in service.yaml with the labels on the Pods, character by character.
  • Using the `latest` tag. A Pod created from image: nginx:latest can run different code from a Pod created an hour later, because latest is re-pointed whenever a new image is pushed. Worse, Kubernetes will not start a rollout when the tag has not changed, so updating the image in the registry does nothing. Pin a version — nginx:1.27, not nginx:latest — and change the tag when you want a new version.
  • Probes that are too aggressive. A liveness probe with a short initialDelaySeconds restarts a container that was still starting up, which makes the restart loop look like a crash. A readiness probe pointed at a path the application does not serve removes every Pod from the Service, which looks like the application is down. Start with generous delays — 5 seconds for readiness and 15 for liveness, as in the example — and tighten them only after watching the application start.

When a Deployment misbehaves and none of these explains it, kubectl describe is the diagnostic tool: kubectl describe deployment web-app for the Deployment’s events, kubectl describe pod <pod-name> for the Pod’s events, including image pull errors and probe failures. The events at the bottom of the output usually name the problem directly.

FAQ

Do I need a Deployment for a single Pod?

Yes, in practice. A single bare Pod has no self-healing: if it crashes or its node dies, nothing replaces it. A Deployment with replicas: 1 gives you that replacement, plus rolling updates and rollback, for no extra cost. Bare Pods are for experiments, not for workloads you care about.

What is the difference between a Deployment and a StatefulSet?

A Deployment is for stateless applications — web servers, APIs — where any Pod is interchangeable with any other. A StatefulSet is for stateful applications — databases — where each Pod has a stable identity, stable storage and an ordered startup. If your Pods need to be told apart, you need a StatefulSet; if they do not, a Deployment is simpler and is the right choice.

Why does my rollout hang with Pods stuck in Pending?

Usually the cluster has no room: the Pods’ resource requests exceed what any node can offer, or a node selector or affinity rule matches no node. kubectl describe pod <pod-name> shows the scheduler’s reason in the events, usually Insufficient cpu or Insufficient memory. Lower the requests, add a node, or remove the constraint that matches nothing.

Can I use a Deployment with Helm?

Yes — Helm charts are mostly Deployments and Services wrapped in templates. Writing the YAML by hand first, as in this tutorial, is the right preparation: a Helm chart is the same objects with placeholders instead of fixed values. Our Helm Tutorial for Beginners builds on exactly this knowledge.

How do I prepare for the CKA exam with Deployments?

Deployments are one of the most-tested objects on the Certified Kubernetes Administrator exam: creating them, scaling them, updating them and rolling them back, all under time pressure. Practise the commands in this tutorial until you can run them without looking them up — kubectl apply, kubectl rollout status, kubectl set image, kubectl rollout undo — and then work through our CKA Certification Guide 2026 for the full exam plan.

Conclusion

A Deployment is three ideas in one object: a desired replica count that self-heals, a Pod template that versions your application, and a rollout mechanism that updates it without downtime and rolls it back when an update goes wrong. The YAML in this tutorial is the whole of it — an apps/v1 Deployment with a selector, a template, resources and probes, plus a Service that gives the Pods a stable address. Learn to read every field in these two files and you can read any Deployment you meet in production, because they are all the same shape with different values.

From here, the next steps are packaging and automation: our Helm Tutorial for Beginners turns these files into a reusable chart, and our CKA Certification Guide 2026 shows how Deployment skills fit into the certification that proves them. But the habit to keep is the one this tutorial practised: write the YAML, check the selector matches the template, apply it, watch the rollout, and know how to undo it. That loop is the daily work of running applications on Kubernetes.

Sources checked 28 Nov 2026: Kubernetes Deployments documentation at kubernetes.io (Deployment → ReplicaSet → Pod ownership; rolling update strategy with maxSurge/maxUnavailable 25% defaults; revisionHistoryLimit default 10; progressDeadlineSeconds default 600s; selector must match template labels; apps/v1 stable since 1.9); Kubernetes rollout documentation at kubernetes.io (kubectl rollout status/history/undo, –to-revision, change-cause annotation); kubernetes.io/releases (1.37 “Garhwal” released 26 Aug 2026; 1.38 planned ~16 Dec 2026) and kubernetes.io/releases/patch-releases (next patch 1.37.3, target 25 Nov 2026); 1.37.3 (25 Nov 2026) confirmed via endoflife.date (updated 26 Nov 2026) — re-check at publication, as the kubernetes.io patch page still listed 1.37.3 as the next patch on 28 Nov. External references: Kubernetes Deployments · Update a Deployment.

—

Scroll to Top