Introduction

Your first Kubernetes deployment is where Kubernetes stops being vocabulary and starts being a system you operate: you submit one Deployment object, controllers create a ReplicaSet and Pods, and the cluster keeps working to hold that state. This lesson builds that Deployment twice, once with commands and once with YAML, so you can feel the difference, not memorise it.

This lesson assumes the cluster from the previous series post, the kind local Kubernetes cluster lab, where you built a multi-node cluster on your own machine. If the words Pod, Node, and Service still feel slippery, skim Kubernetes concepts explained first, then come back. Nothing here needs a cloud account, and every command runs against that local cluster.

Here is an illustrative composite scenario, drawn from a pattern every platform team recognises rather than one named incident. An engineer creates a Deployment with a single kubectl command during a late-night test. It works. Two weeks later a teammate scales it, someone else edits the image by hand, and nobody can say which change came from where. The cluster is healthy, but the knowledge of how it got that way lives in three terminal histories. That gap, not the YAML syntax, is what this lesson is really about.

The 5-minute takeaway: imperative commands tell Kubernetes what to do right now; declarative YAML tells Kubernetes what should exist. Use commands to learn and to generate starting YAML, then manage anything you care about from files. By the end of this lesson you will have created a Deployment both ways, verified the rollout, and know exactly which style to reach for next time. The next series post, Kubernetes Pod Lifecycle: Pending, Running, CrashLoop and Termination, picks up where this one ends: what those Pods are doing after your Deployment creates them.


1. What your first Kubernetes deployment actually creates

When you submit your first Kubernetes deployment, you create exactly one object, a Deployment, and Kubernetes does the rest: the Deployment controller creates a ReplicaSet, the ReplicaSet creates Pods, and the scheduler places those Pods on nodes. You never create the Pods directly, and that indirection is the whole point.

Think of the Deployment as a stored instruction, not a running process. The API server validates your object, writes it to etcd, and returns success. Then controllers wake up. The Deployment controller reads your Pod template, computes a hash of it, and creates a ReplicaSet carrying that hash. The ReplicaSet controller counts Pods matching its selector, finds zero, and creates Pods until the count matches your replica request. The scheduler binds each Pod to a node, and the kubelet on that node pulls the image and starts the container.

This chain explains behaviour that confuses beginners. Deleting a Pod does not shrink your application, because the ReplicaSet notices the count dropped and creates a replacement. Editing the Deployment's image does not modify running Pods in place, because Pods are not edited; the Deployment creates a new ReplicaSet and shifts replicas across. Once you see the Deployment as the durable record and Pods as disposable instances, most of Kubernetes starts to make sense.

It also explains why a Deployment is the right first workload. A bare Pod gives you none of this: no replacement, no scaling, no rolling update. A Deployment gives you all three from one small object. Choosing between Deployment, StatefulSet, and DaemonSet is a separate decision, covered in Deployment vs StatefulSet vs DaemonSet; for a stateless web process, Deployment is the default answer.


2. Creating your first Kubernetes deployment the imperative way

The imperative way to create your first Kubernetes deployment is a single command, kubectl create deployment web --image=nginx:alpine --replicas=2, which tells the API server to build a Deployment named web running two copies of the image. It is the fastest path from an empty cluster to running Pods, and it is worth doing first.

bash
kubectl create deployment web --image=nginx:alpine --replicas=2
kubectl get deployment web
kubectl get pods -l app=web

Run those three commands against your kind cluster. The first creates the Deployment. The second shows the Deployment's readiness counts. The third lists the Pods the ReplicaSet created, selected by the app=web label that kubectl stamped on them automatically. Within seconds you should see two Pods reach Running, assuming the image pulls cleanly.

Notice what the command did for you. It chose the apiVersion, built the selector, matched the template labels to that selector, and set the container name from the image. That convenience is real, and it is why imperative commands are excellent for learning: you can watch the controller chain from the previous section happen in front of you without writing any YAML first.

Now notice the cost. The command you typed exists only in your shell history. If a teammate asks what is running, you cannot point at a file; you have to interrogate the cluster. If you delete the Deployment and want it back, you must remember the exact flags. And if you run the same create command again, it fails, because create insists the object must not already exist. Imperative commands are one-shot instructions. They are honest about that, and for a throwaway test that is fine. For anything you will touch twice, you want the second style.


3. Generating YAML for your first Kubernetes deployment with dry-run

The bridge between the two styles is generating YAML for your first Kubernetes deployment with kubectl create deployment web --image=nginx:alpine --replicas=2 --dry-run=client -o yaml, which prints a complete manifest without sending anything to the cluster. You get a correct skeleton, edit it, and then apply it declaratively.

bash
kubectl create deployment web --image=nginx:alpine --replicas=2 \
  --dry-run=client -o yaml > web-deployment.yaml

The --dry-run=client flag tells kubectl to build the object locally and stop before the API call. Nothing is created, so you can run it as often as you like. The -o yaml flag prints the object in the same shape the API server would store. Redirecting it to a file gives you a manifest whose selector and template labels already agree, which is the part people most often get wrong when typing YAML from memory.

Generated output carries a few empty fields, typically strategy: {}, resources: {}, and status: {}. You can delete them; the API server ignores empty maps, and status is owned by the controllers anyway. What matters is what you add next: a container port, resource requests, and probes, the fields that turn a demo into something you would trust. We will add those in the declarative version below.

This generate-edit-apply loop is the single most useful kubectl habit for a beginner. It removes blank-page anxiety, it keeps labels consistent, and it produces a file you can commit. Senior engineers use it constantly, not because they cannot write YAML, but because generated YAML starts correct. The kubectl master guide covers the wider command set; this one flag combination earns its place in your daily workflow from day one.


4. Reading the YAML behind your first Kubernetes deployment

Every manifest for your first Kubernetes deployment has four top-level fields, apiVersion, kind, metadata, and spec, and reading them in that order tells you what the object is, what it is called, and what state you are asking for. The spec is where your intent lives; everything else is framing.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:alpine
          ports:
            - containerPort: 80

apiVersion: apps/v1 names the API group and version that define the Deployment type, and kind: Deployment names the type itself. Together they tell the API server which schema to validate against. metadata carries identity: the name, the namespace if you set one, and labels used for organisation and selection. Nothing in metadata runs your code; it describes the object.

spec is the desired state. replicas is the count the ReplicaSet will defend. selector declares which Pods this Deployment owns. template is a complete Pod definition nested inside the Deployment, with its own metadata and spec, and it is the stencil every Pod is stamped from. When you change the template, the Deployment treats it as a new revision and rolls Pods across. When you change only replicas, no new revision appears; the existing ReplicaSet simply grows or shrinks.

Read the nesting carefully, because it is the most common beginner stumble. There are two spec blocks and two labels blocks, and they belong to different objects. The outer spec configures the Deployment. The inner spec, under template, configures each Pod. A field in the wrong spec is either rejected by validation or, worse, silently ignored if it lands somewhere the schema tolerates. Indentation is not decoration in YAML; it is the structure itself.


5. Labels and selectors in your first Kubernetes deployment

In your first Kubernetes deployment, the selector under spec.selector.matchLabels must match the labels on the Pod template, because that match is how the Deployment recognises which Pods it owns. The API server rejects a Deployment whose template labels do not satisfy its selector, and the selector cannot be changed after creation.

There are three label locations in the manifest, and keeping them straight prevents a whole class of silent failures. The labels on the Deployment's own metadata are organisational; they help you list and group Deployments. The selector is functional; it is a query the controllers run continuously. The template labels are stamped onto every Pod the ReplicaSet creates, and they are what the selector queries. The second and third must agree, or the controller would create Pods it cannot recognise as its own.

Immutability is deliberate. If you could edit a selector in place, the existing Pods would instantly stop matching, the controller would treat them as foreign, and it would create a second full set alongside them. Kubernetes refuses that footgun: to change a selector, you delete the Deployment and recreate it. The practical rule follows directly. Keep the selector minimal and stable, usually a single app label, and put changeable labels such as version or tier on the template only, where they can evolve without orphaning Pods.

Overlapping selectors are the related trap. Kubernetes does not stop two Deployments from selecting the same Pods, so if two controllers both match app=web, they fight over the same Pods and the replica count oscillates. Give every Deployment labels that are uniquely its own. When a Service later selects Pods by label, it uses the same mechanism, which is why a selector mismatch so often shows up as a Service with no endpoints. Get the contract right here and several later lessons become easier.


6. Applying your first Kubernetes deployment declaratively

Applying your first Kubernetes deployment declaratively means running kubectl apply -f web-deployment.yaml, which sends the file's desired state to the API server and lets Kubernetes work out whether to create or update. Running the same apply twice is safe: the second run reports the object unchanged instead of failing.

bash
kubectl apply -f web-deployment.yaml
kubectl apply -f web-deployment.yaml

The first command creates the Deployment. The second prints deployment.apps/web unchanged. That idempotence is the operational heart of declarative management. Your file describes the end state, not a sequence of steps, so the tool can converge the cluster toward it from any starting point. A teammate can run the same file on a fresh cluster and get the same result, which no shell history can promise.

Under the hood, apply compares three versions of the object: the last configuration you applied, the new configuration in your file, and the live object in the cluster. Fields you removed from the file are removed from the object; fields other actors set, such as annotations from controllers, are left alone. You do not need the merge details on day one. You need the discipline the model rewards: edit the file, then apply the file, every time.

Before applying a change to something that matters, preview it. kubectl diff -f web-deployment.yaml shows what would change without changing it, and kubectl apply --dry-run=server -f web-deployment.yaml asks the API server to validate the object, including admission checks, without persisting it. These two commands turn apply from a leap of faith into a reviewed change, and they cost seconds. Build the habit now, while the stakes are a local cluster.


7. Imperative vs declarative for your first Kubernetes deployment

For your first Kubernetes deployment, imperative commands win on speed and declarative YAML wins on everything that happens after the first five minutes: repeatability, review, rollback, and teamwork. The practical answer is not choosing one forever; it is using commands to explore and generate, then files to manage.

Question Imperative commands Declarative YAML
How do you express intent? A verb: create, scale, set image A file describing desired state
Run it twice Create fails if the object exists Apply converges and reports unchanged
Where is the record? Shell history and memory The file, ideally in Git
Code review Nothing to review Diff the file before applying
Expressing probes, resources, volumes Awkward or impossible via flags Natural, full schema available
Rollback Reconstruct the old command Reapply the previous file version
Best for Learning, one-off tests, generating YAML Anything shared, repeated, or production

Read the table as a lifecycle, not a contest. On day one, the imperative command teaches you the controller chain because it removes every other variable. The dry-run flag then converts that command into a file, and from that moment the file is the source of truth. Teams that skip the conversion step end up with clusters nobody can reproduce, which is a quiet form of technical debt that surfaces during incidents.

There is one more distinction worth naming. Kubernetes also supports imperative object configuration, where you use kubectl create -f or kubectl replace -f with files but still issue one-shot verbs. It has niche uses, mainly when you need exact replacement semantics. For a first deployment, plain apply is the right default, and mixing management styles on the same object is where surprises breed. Pick apply for the object and stay with it.


8. Changing your first Kubernetes deployment without creating drift

Changing your first Kubernetes deployment safely means editing the YAML and reapplying it, because imperative edits such as kubectl scale or kubectl set image change the cluster without changing your file, and the next apply silently overwrites them. That gap between file and cluster is drift, and drift is where confusion lives.

Scaling shows the contrast cleanly. Imperatively, kubectl scale deployment web --replicas=3 works instantly. Declaratively, you change replicas: 2 to replicas: 3 in the file and apply. Both end at three Pods. The difference appears a week later: the file still says two, so the next person to apply an unrelated change scales you back down without noticing. The declarative path makes the change visible in a diff, where a reviewer can ask whether three is still right.

Image updates behave the same way, with higher stakes. Editing the image tag in the template and applying triggers a rolling update: the Deployment creates a new ReplicaSet, brings up new Pods, waits for them to become ready, and retires the old ones. kubectl set image triggers the identical rollout, but leaves your file pointing at the old tag. When the rollout misbehaves at 2 a.m., the file is what the on-call engineer trusts, and a stale file sends them debugging the wrong version.

None of this makes imperative changes forbidden. During an incident, scaling from the terminal can be the fastest safe move. The rule is to reconcile afterwards: update the file to match what you did, apply it, and confirm the diff is empty. Drift is only dangerous when it is forgotten. Treat the file as the memory of the system, and your future self will thank you during the next incident review.


9. Verifying your first Kubernetes deployment rolled out cleanly

Verifying your first Kubernetes deployment means watching the rollout converge, not just seeing the apply succeed: run kubectl rollout status deployment/web, confirm the Pods are Ready, and read the Deployment's conditions before you call it done. Apply succeeding only proves the API server accepted your object.

bash
kubectl rollout status deployment/web --timeout=120s
kubectl get deployment web
kubectl get pods -l app=web -o wide
kubectl describe deployment web

kubectl rollout status blocks until the rollout completes or the timeout expires, which makes it the right gate in scripts and pipelines. kubectl get deployment summarises the counts: READY shows ready replicas over desired, UP-TO-DATE shows Pods on the current template, and AVAILABLE shows Pods that have been ready long enough to count as available. When all three agree with your replica count, the rollout has converged.

kubectl describe deployment is where you look when they do not agree. Its Conditions section reports Progressing and Available, and a stalled rollout eventually surfaces a ProgressDeadlineExceeded reason. Its Events section shows what the controllers did and what failed. Read describe output before changing anything; guessing at a stuck rollout by reapplying the same file rarely helps, because the file was probably fine and the Pods are telling you the real story.

Finish verification by exercising the workload, not just observing it. Port-forward to the Deployment and request a page:

bash
kubectl port-forward deployment/web 8080:80
curl -s http://localhost:8080 | head

A response proves the full chain works: Pods running, containers serving, and the port wiring correct. That end-to-end check is the difference between "Kubernetes accepted my YAML" and "my application is up", and only the second one matters to anyone waiting on you.


10. Troubleshooting your first Kubernetes deployment

When your first Kubernetes deployment misbehaves, the failure almost always announces itself in one of four places: the apply error, the Pod status, the Pod events, or the container logs. Reading them in that order turns a stuck first deployment from guesswork into a short checklist.

Symptom Likely cause First check Fix
Apply rejected: selector does not match template labels matchLabels and template labels disagree Compare spec.selector with spec.template.metadata.labels Make them identical, then reapply
Apply rejected: field is immutable You edited the selector on an existing Deployment kubectl get deployment web -o yaml Delete and recreate the Deployment with the new selector
Create fails: already exists Imperative create against an existing object kubectl get deployment web Switch to kubectl apply -f for updates
Pods stuck in Pending No node can schedule the Pod, often resource requests too large for the node kubectl describe pod <pod> events Lower requests or add node capacity
Pods in ImagePullBackOff Image name, tag, or registry access is wrong kubectl describe pod <pod> events Correct the image reference or pull secret
Pods in CrashLoopBackOff Container starts and exits repeatedly kubectl logs <pod> --previous Fix the application error the logs show
Rollout never completes New Pods never become Ready kubectl rollout status then kubectl describe deployment Fix the Pod-level cause; do not keep reapplying
Service has no endpoints Service selector matches no Pod labels kubectl get endpoints and Pod labels Align the Service selector with template labels

Two habits make this matrix work. First, always read events before logs for scheduling and image problems, because the container may never have started, in which case there are no logs to read. kubectl describe pod puts events at the bottom, and the most recent warning usually names the problem plainly. Second, change one thing at a time. A first deployment is small enough that disciplined single changes converge fast; shotgun edits create new failures faster than you can attribute them.

For the deeper failure modes, use the dedicated runbooks instead of improvising. How to fix CrashLoopBackOff in Kubernetes covers exit codes and probe failures in depth, and the next roadmap lesson walks through each Pod phase so statuses like Pending and CrashLoopBackOff stop being mysteries. Your job in this lesson is narrower: recognise which row of the matrix you are in, and run its first check.


11. Production habits to build into your first Kubernetes deployment

The production habits worth building into your first Kubernetes deployment are few and cheap: pin the image to a specific tag, set resource requests, add a readiness probe, run in a named namespace, and keep the manifest in Git. Each one prevents a class of incident you would otherwise meet later, at higher cost.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: apps
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:alpine
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              memory: 256Mi
          readinessProbe:
            httpGet:
              path: /
              port: 80
            initialDelaySeconds: 3
            periodSeconds: 5

Pinning matters because a floating tag such as latest can change under you between two applies of the same file, which breaks the promise that the file describes the system. Use a specific tag from your registry, and treat updating it as a deliberate, reviewed change. Resource requests matter because the scheduler uses them to place Pods; without them, Kubernetes cannot reason about node capacity, and Pods land wherever, including on nodes that cannot feed them.

The readiness probe is what makes rollouts safe. Without it, Kubernetes considers a Pod ready the moment its container starts, and a rolling update can retire healthy old Pods in favour of new ones that are still warming up or already failing. With it, traffic and rollout progress wait for evidence the application can serve. A namespace keeps your objects grouped and lets you apply quotas and policies later without renaming anything.

Finally, commit the file. Git history is your audit trail, your rollback mechanism, and your answer to "what changed?" during an incident. These five habits are the day-one subset of a much larger discipline; Kubernetes best practices covers the full production treatment, from disruption budgets to security profiles, when you are ready for it.


12. Final checklist for your first Kubernetes deployment

Your first Kubernetes deployment is done when you can delete it and recreate it from the file alone, watch the rollout converge, and explain what each controller did along the way. Run this checklist against your kind cluster to prove all three before moving to the next lesson.

  • [ ] Created the Deployment imperatively and watched the ReplicaSet create Pods
  • [ ] Generated YAML with --dry-run=client -o yaml and cleaned the empty fields
  • [ ] Confirmed spec.selector.matchLabels matches the Pod template labels exactly
  • [ ] Applied the file with kubectl apply -f and reapplied it to see "unchanged"
  • [ ] Previewed a change with kubectl diff -f before applying it
  • [ ] Scaled by editing replicas in the file, not only from the terminal
  • [ ] Verified with kubectl rollout status and checked READY, UP-TO-DATE, and AVAILABLE counts agree
  • [ ] Reached the application through kubectl port-forward and got a real response
  • [ ] Added resource requests, a readiness probe, and a pinned image tag
  • [ ] Committed the manifest to Git
  • [ ] Deleted the Deployment and recreated it from the file to prove reproducibility

If any box stays unticked, the troubleshooting matrix in the previous sections maps the symptom to its first check. Do not rush past a failing item: the habits in this checklist are the ones every later lesson assumes, from Services and Ingress to rollbacks and GitOps. A Deployment you can reproduce from a file, verify with rollout status, and explain controller by controller is a solid foundation. The next lesson builds directly on it by following a single Pod through its lifecycle, from Pending to Running to termination, so the statuses you saw in the matrix become a story you can read at a glance.

Frequently Asked Questions

What should my first Kubernetes deployment include?

Your first Kubernetes deployment should include a name, a replica count, a selector that matches the Pod template labels, and one container with an image and port. Add resource requests and a readiness probe as soon as the basics work. Generate the starting YAML with kubectl create deployment --dry-run=client -o yaml, edit it, and apply it with kubectl apply -f.

How is a first Kubernetes deployment different imperatively vs declaratively?

Imperatively, you issue verbs such as kubectl create deployment and kubectl scale, and Kubernetes acts immediately with no file recording your intent. Declaratively, you write YAML describing the desired state and run kubectl apply -f, and Kubernetes converges the cluster toward it. Imperative is faster to start; declarative is repeatable, reviewable, and safe to reapply.

How do I generate YAML for my first Kubernetes deployment without creating anything?

Add --dry-run=client -o yaml to a create command: kubectl create deployment web --image=nginx:alpine --replicas=2 --dry-run=client -o yaml > web-deployment.yaml. kubectl builds the object locally, prints valid YAML with matching selector and template labels, and sends nothing to the cluster. Edit the file, remove empty fields, then apply it.

Why must the selector match the template labels in my first Kubernetes deployment?

The selector is how the Deployment and its ReplicaSet recognise which Pods they own, and the template labels are what new Pods carry. If they disagree, the controller would create Pods it cannot recognise, so the API server rejects the Deployment. The selector is also immutable after creation, so keep it minimal and stable, usually a single app label.

What does kubectl apply do for my first Kubernetes deployment that create does not?

kubectl create makes a new object and fails if it already exists. kubectl apply compares your file with the live object and the last applied configuration, then creates or updates as needed, reporting "unchanged" when nothing differs. That idempotence lets you manage the whole lifecycle of a Deployment from one file, which is why apply is the production default.

How do I verify my first Kubernetes deployment actually worked?

Run kubectl rollout status deployment/web and wait for it to report success, then check kubectl get deployment web shows READY, UP-TO-DATE, and AVAILABLE counts matching your replica count. Confirm Pods are Ready with kubectl get pods -l app=web, and finish by requesting the application through kubectl port-forward to prove the full chain serves traffic.

Should I manage my first Kubernetes deployment imperatively in production?

No. Imperative commands are for learning, quick tests, and generating YAML. In production, manage Deployments declaratively from version-controlled files, because imperative edits create drift: the cluster changes but your file does not, and the next apply silently overwrites the manual change. If an incident forces a terminal change, update the file afterwards and reapply it.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →