Deployments in Kubernetes

Deployments in Kubernetes

How Kubernetes keeps the right number of copies of your application running, updates them without downtime, and rolls back when a release goes wrong. A beginner-friendly guide to the most-used workload object in the cluster.

Imagine you manage a bakery chain. You tell the head office, “Every shop must always have three bakers on duty, all using the current recipe.” You do not phone each shop every morning. If a baker falls sick, someone is sent to replace them. When the recipe changes, bakers are swapped over shop by shop so that customers are never left without bread. That head office instruction is what a Deployment is in Kubernetes: a standing order that says what should be running, and a manager that works tirelessly to keep reality matching it.

1The Problem Deployments Solve

To appreciate the tool, feel the pain of living without it.

Running one pod by hand

A pod is the smallest thing Kubernetes runs, a small shared home for one or more containers. You could create a single pod directly and it would work. But a bare pod is fragile. If the machine it lives on breaks, the pod is gone and nobody replaces it. If you want ten copies, you must create ten pods yourself. If you want to release a new version, you must delete the old pods and start new ones by hand, and customers see errors in between.

What we really want

1

Keep N copies alive

If a pod disappears for any reason, a new one should appear automatically.

2

Scale easily

Changing the number of copies should be a single small edit, not a manual chore.

3

Update safely

A new version should replace the old one gradually, with no visible outage.

4

Undo mistakes

If the new version is bad, going back should be quick and reliable.

A Deployment delivers all four wishes. It is the standard way to run stateless applications, meaning programs that do not keep important data on their own local disk, such as web servers and APIs.

Simple Analogy

Hiring temporary staff one by one and supervising them yourself is tiring. A staffing agency that promises “we will always keep three people at your counter” takes the work off your hands. A Deployment is that agency.

2What Exactly Is a Deployment?

A Deployment is a Kubernetes object that declares the desired state of a set of identical pods and manages how they change over time.

You describe what you want, and Kubernetes makes it so. A Deployment description mainly contains three things.

Part 1

Pod template

The blueprint for each pod: which container image, which ports, how much memory and processing power, and which health checks.

Part 2

Replica count

How many identical copies of the pod should be running.

Part 3

Selector

The label rule that tells the Deployment which pods belong to it.

Part 4

Update strategy

The rules for how old pods are replaced by new ones during a release.

Simple Analogy

A Deployment is a cookie cutter and a quantity. The cutter is the pod template, the quantity is the replica count, and the baker keeps stamping out cookies until the tray always holds exactly that many.

i
Desired State

The heart of Kubernetes is the idea of desired state. You state the goal, and controllers compare it with reality again and again, correcting any gap. A Deployment is a perfect example.

3The Chain of Command: Deployment, ReplicaSet and Pods

A Deployment does not manage pods directly. It has a helper in between.

Between a Deployment and its pods sits an object called a ReplicaSet. A ReplicaSet has one simple job: make sure a specific number of identical pods are running. The Deployment, in turn, manages ReplicaSets and decides which one should be active.

graph TD
  D["Deployment"] --> R1["ReplicaSet for version 1"]
  D --> R2["ReplicaSet for version 2"]
  R1 --> P1["Pod"]
  R1 --> P2["Pod"]
  R2 --> P3["Pod"]
  R2 --> P4["Pod"]
  R2 --> P5["Pod"]
        
FIG 1 — A Deployment owns ReplicaSets, which own Pods

Why the extra layer?

Each version of your application gets its own ReplicaSet. During an update, the Deployment slowly grows the new version’s ReplicaSet while shrinking the old one. The old ReplicaSet is kept, at zero pods, as a ready-made snapshot of the previous version, which is exactly what makes quick rollbacks possible.

Simple Analogy

A regional manager, the Deployment, oversees several shift supervisors, the ReplicaSets. Each supervisor is responsible for one crew working to one version of the recipe. When the recipe changes, the manager moves staff from the old supervisor’s crew to the new one’s, and keeps the old crew’s roster in the drawer in case it is needed again.

!
Do Not Edit by Hand

You normally work only with the Deployment. Editing the ReplicaSets or pods that it owns is a bad idea, because the Deployment will simply change them back.

4Labels and Selectors: How Ownership Is Decided

Kubernetes uses simple name tags to know which pods belong to whom.

A label is a small key and value pair, such as “app equals shop,” attached to an object. A selector is a rule that picks objects by their labels. A Deployment includes a selector that matches the labels in its pod template, and that is how it knows which pods are its own.

The same labels connect a Service

A Service uses a selector too. When the Service’s selector matches the pods’ labels, traffic flows to them. This is how a stable front door finds the constantly changing pods behind a Deployment.

Labels must match consistently

If the Deployment’s selector and pod template labels disagree, Kubernetes will refuse the Deployment. If a Service’s selector does not match the pods, the Service will have nobody behind it.

Simple Analogy

Colored wristbands at a festival show which group each person belongs to. The gate staff look at the wristband, not the name, to decide where to send them. Labels are wristbands and selectors are the staff reading them.

5Self-Healing: Keeping the Count Right

The Deployment quietly repairs the damage when pods disappear.

The ReplicaSet constantly counts the pods that match its rule. If the count is too low, because a pod crashed, a machine died or someone deleted a pod, it creates new ones. If the count is too high, it removes extras. You never need to restart anything manually.

1

A machine fails

The pods on it stop responding and Kubernetes marks them as lost.

2

The count drops

Where three pods were wanted, only two are found.

3

A replacement is created

The ReplicaSet creates a new pod, and the scheduler places it on a healthy machine.

4

The count is restored

Three pods run again, and the Service starts sending traffic to the new pod once it is ready.

Simple Analogy

A lifeguard’s rule is “always four guards on the beach.” If one leaves, the supervisor calls in another. Nobody asks whether it is necessary; the rule alone triggers the action.

i
Two Layers of Healing

A crashed container is restarted inside its pod by the node’s agent. A missing pod is replaced by the ReplicaSet. Together they cover most common failures.

6Scaling Up and Down

Changing the number of copies is just changing a number.

To handle more visitors, you raise the replica count. The ReplicaSet creates the extra pods, and the scheduler finds room for them. To save money in quiet times, you lower the count and the extra pods are shut down gracefully. Scaling does not create a new ReplicaSet, because the pod blueprint has not changed.

Way 1

Manual scaling

A person changes the replica count when they know demand will rise, such as before a planned sale.

Way 2

Horizontal Pod Autoscaler

A companion object watches measurements such as processor use and adjusts the replica count automatically within limits you set.

Way 3

Cluster autoscaling

If there is no space left for new pods, a further component asks the cloud for more machines.

Simple Analogy

A supermarket opens more billing counters when queues grow and closes them when they shrink. The counters are identical, so opening another one needs no new training.

!
Watch the Autoscaler

When an autoscaler is in charge, do not also hard-code a replica count in the Deployment file, or the two will fight over the number.

7Rolling Updates: Replacing Pods Without Downtime

The signature feature of a Deployment.

When you change the pod template, for example by choosing a new container image, the Deployment starts a rollout. It creates a new ReplicaSet for the new version and gradually shifts pods from the old one to the new one. At every moment, enough pods are serving users, so nobody notices the change.

sequenceDiagram
  participant You
  participant D as Deployment
  participant Old as Old ReplicaSet
  participant New as New ReplicaSet
  You->>D: Change pod template
  D->>New: Create with zero pods
  D->>New: Add first new pod
  New-->>D: Pod ready
  D->>Old: Remove one old pod
  D->>New: Add next new pod
  New-->>D: Pod ready
  D->>Old: Remove next old pod
  Note over D: Repeat until all pods are new
        
FIG 2 — A rolling update step by step

The two dials that control speed and safety

Max surge

How many extra pods above the desired count may exist during the update. A higher number makes the rollout faster but uses more resources temporarily.

Max unavailable

How many pods may be missing from the desired count during the update. Setting this to zero means capacity never dips, at the price of needing extra room to start new pods first.

By default, both dials are set to a quarter of the desired count. You can tune them depending on whether you value speed, spare capacity or unbroken service the most.

Simple Analogy

Repainting a busy road is done one lane at a time so traffic keeps moving. Max surge is how many extra lanes you may open at once, and max unavailable is how many lanes you may close at once.

8Readiness Checks: The Gatekeepers of a Safe Rollout

A rolling update is only as safe as the health checks behind it.

The Deployment moves on to the next step only after a new pod reports that it is ready. Readiness is decided by a readiness probe, a small periodic check that asks the application whether it can serve requests. Without it, Kubernetes assumes a pod is ready the moment its container starts, even if the program inside is still loading and would fail real requests.

1

Startup probe

Gives slow-starting applications time to boot before other checks begin.

2

Readiness probe

Decides whether the pod should receive traffic and whether the rollout may proceed.

3

Liveness probe

Detects a frozen application and asks Kubernetes to restart the container.

!
Common Mistake

Skipping readiness probes. The Deployment then declares success while users receive errors from pods that are not truly ready.

Simple Analogy

A relay race baton is only passed when the next runner is in position and ready to take it. The readiness probe is the runner raising a hand to say, “I am ready.”

9Rollbacks: The Undo Button

Every release can be reversed.

Because old ReplicaSets are kept, returning to a previous version is fast. Kubernetes simply scales the old ReplicaSet back up while scaling the newer one down, using the same careful rolling approach. Each such state is called a revision, and you can view the revision history and choose which one to return to.

flowchart TD
  A["Release version 2"] --> B{"Is it healthy?"}
  B -->|Yes| C["Keep version 2"]
  B -->|No| D["Roll back to version 1"]
  D --> E["Old ReplicaSet scales up"]
  E --> F["Bad ReplicaSet scales down"]
        
FIG 3 — Deciding between keeping and rolling back

How much history is kept

The Deployment remembers a limited number of old revisions, ten by default, controlled by the revision history limit. Setting it too low limits how far back you can go. Setting it too high leaves clutter of unused ReplicaSets.

When the rollout gets stuck

If new pods never become ready, the Deployment stops advancing and, after a waiting period called the progress deadline, marks the rollout as failed. It does not automatically undo the change, but because the old pods are still serving traffic, users are usually protected while you investigate or roll back yourself.

Simple Analogy

A word processor keeps previous versions of your document, so if a change ruins it you can jump back to yesterday’s copy. Old ReplicaSets are the saved versions.

10What Triggers a New Rollout, and What Does Not

A common source of confusion for beginners.

Change you makeStarts a rollout?What happens
New container image versionYesA new ReplicaSet is created and pods are replaced gradually
Different environment settings in the pod templateYesTreated as a new version of the template
New resource requests or limitsYesPods are recreated with the new values
Changed health check settingsYesThe template changed, so pods are replaced
Changed replica count onlyNoThe existing ReplicaSet simply adds or removes pods
Changed update strategy dials onlyNoApplies to the next rollout, no pods replaced now
Change to a ConfigMap that the pods readNot by itselfPods may not notice unless restarted or unless the template changes
i
A Handy Trick

When only a ConfigMap or Secret has changed, a controlled restart of the Deployment triggers a normal rolling replacement so all pods pick up the new values gradually.

11Update Strategies: Rolling vs Recreate

Deployments support two built-in ways of replacing pods.

Strategy 1

Rolling update

The default. Pods are swapped gradually so the application stays available. Old and new versions run side by side for a while.

Strategy 2

Recreate

All old pods are stopped first, then new ones are started. There is a short outage, but the two versions never run at the same time.

When would you pick Recreate?

Some applications cannot tolerate two versions running together, for example when a new version changes the shape of stored data in a way the old version cannot read, or when only one instance may hold a certain resource at a time. In those cases a brief pause is the safer trade.

!
Design for Two Versions

With rolling updates, old and new versions serve users at the same time. Make sure your changes, especially to data formats and message contracts, work with both versions during the transition.

Simple Analogy

Rolling is repaving a road one lane at a time. Recreate is closing the whole road for a weekend. The second is simpler and safer for the surface, but every driver feels it.

12Blue-Green and Canary: Advanced Release Styles

Kubernetes has no dedicated button for these, but Deployments make them possible.

Blue-green

Run two complete environments: the current one, called blue, and the new one, called green. Once the green environment passes its checks, the Service or routing layer is switched to point at it in one move. If problems appear, switching back is just as quick. The cost is temporarily running double the capacity.

Canary

Send a small share of real traffic, say five percent, to the new version while everyone else uses the old one. If measurements look healthy, increase the share gradually. The name comes from canaries once used in mines to warn of danger before the miners were harmed.

Tools that help

Ingress controllers, service meshes and progressive delivery tools can split traffic by percentage and automate the promotion or rollback steps based on live measurements.

graph LR
  U["Users"] --> S["Traffic router"]
  S -->|"95 percent"| A["Deployment: stable version"]
  S -->|"5 percent"| B["Deployment: canary version"]
        
FIG 4 — A canary release splitting traffic between two Deployments

13Resources, Placement and Spreading

A Deployment tells pods what they need and where they should not all sit together.

Requests and limits

A request is the amount of memory and processing power a pod needs in order to be placed. A limit is the most it may use. Setting both helps the scheduler pack machines wisely and stops one greedy pod from starving neighbors.

Spreading copies apart

If all copies of your application land on one machine, a single failure takes everything down. Spread rules ask the scheduler to distribute pods across machines and across zones, so a single failure removes only a fraction of your capacity.

Disruption budgets

A Pod Disruption Budget states the minimum number of pods that must stay available during voluntary events, such as machine maintenance and upgrades, so routine work does not accidentally remove too many at once.

Simple Analogy

A wise airline does not put every experienced pilot on one flight. Spread rules are the same idea for pods: do not keep all your eggs in one basket.

14Deployment vs Other Workload Types

A Deployment is not the answer to every question.

Workload typeBest forKey trait
DeploymentStateless web apps, APIs, workersInterchangeable pods, easy scaling and updates
StatefulSetDatabases and clustered softwareStable names, ordered start-up and dedicated storage per pod
DaemonSetNode-level helpers such as log or monitoring agentsOne pod on every node, or on selected nodes
JobOne-time tasks that run to completionFinishes and stops, retrying on failure
CronJobScheduled recurring tasksCreates Jobs on a timetable
Bare podQuick experiments onlyNo replacement if it fails
Simple Analogy

Deployments are like interchangeable cashiers at a supermarket: any cashier can serve any customer. A StatefulSet is like named doctors in a clinic, where each patient has their own doctor and records. Using the wrong one causes confusion.

15Security Considerations

The pod template is where most Deployment security choices are made.

Control 1

Run as a non-administrator

Set containers to run as ordinary users and prevent them from gaining extra powers.

Control 2

Trusted, fixed images

Use images from sources you trust and pin exact versions rather than the moving label “latest.”

Control 3

Secrets kept out of images

Provide passwords and keys through Secret objects, never baked into the image or the file that anyone can read.

Control 4

Read-only filesystems

Where possible, prevent the container from writing to its own filesystem so attackers cannot alter the software.

Control 5

Least-privilege service account

Give the pods only the cluster permissions they truly need.

Control 6

Network restrictions

Use network policies so pods accept traffic only from the sources that should reach them.

Simple Analogy

Every new employee gets a badge that opens only the doors their job requires. The pod template is the badge form, and security settings are the list of doors.

16Monitoring and Troubleshooting a Deployment

Know what healthy looks like, and what to check when it is not.

Numbers worth watching

Desired
How many pods you asked for
Ready
How many are actually serving traffic
Updated
How many run the newest template

When the desired, ready and updated numbers all agree, the Deployment is healthy and complete. A gap between them is your first clue that something needs attention.

A calm troubleshooting path

1

Check the rollout status

Is it progressing, complete or stuck past its progress deadline?

2

Look at the pods

Are they pending, crash-looping, or failing to pull their image?

3

Read events and descriptions

Events explain why a pod cannot be scheduled, such as not enough memory or processing power on any node.

4

Read the container logs

Application errors often explain failing health checks.

5

Verify the Service connection

Confirm labels match and readiness passes so the Service actually sends traffic to the pods.

6

Roll back if needed

If users are affected and the cause is not obvious, return to the last good revision first, and investigate afterwards.

17Advantages and Trade-offs

A strong default with some boundaries.

Advantages

  • Automatic replacement of failed pods
  • Simple scaling by changing one number or using an autoscaler
  • Rolling updates with no downtime when configured well
  • Quick rollbacks using kept revision history
  • Declarative, reviewable and easy to store in version control
  • Works naturally with Services, autoscalers and disruption budgets

Disadvantages / Trade-offs

  • Meant for stateless applications, not for identity-sensitive software
  • Old and new versions run together during rollouts
  • Rollouts are only as safe as your health checks
  • No built-in canary or blue-green switch, so extra tools are needed
  • Rollbacks change pods but never undo changes to external data

18Anti-Patterns to Avoid

Mistakes that appear in many real clusters.

ANTI-PATTERN-01 Avoid
Problem

Using the moving image label “latest” in the pod template.

Why It’s Harmful

Different pods may pull different actual versions, rollbacks cannot reliably restore a known state, and changing the image does not always trigger a rollout.

Correct Approach

Use exact, unique version tags, or content digests, so every rollout and rollback refers to a precise build.

ANTI-PATTERN-02 Avoid
Problem

Running with no readiness probe, no resource requests and only a single replica.

Why It’s Harmful

Updates cause visible downtime, the scheduler cannot place pods sensibly, and any failure removes the whole application.

Correct Approach

Run at least two or three replicas for important services, define probes and set sensible requests and limits.

ANTI-PATTERN-03 Avoid
Problem

Running a database or other identity-sensitive application as a plain Deployment with local storage.

Why It’s Harmful

Pods are interchangeable and disposable. Data on local storage is lost when a pod is replaced, and copies can conflict with one another.

Correct Approach

Use a StatefulSet with persistent storage, or a managed database service.

ANTI-PATTERN-04 Avoid
Problem

Changing live objects by hand and never updating the stored files.

Why It’s Harmful

The written record no longer matches reality, and the next automated apply can silently undo the manual fix.

Correct Approach

Make every change through version-controlled files and reviewed changes so they remain the single source of truth.

19Real-World Situations

How Deployments show up in daily engineering.

An online shop’s checkout service

Three pods handle checkout. During a sale, an autoscaler raises the count to twenty. When a new version is released mid-day, a rolling update swaps pods gradually while shoppers continue paying.

A streaming platform’s recommendation API

Teams release many times a day. Canary releases send a small slice of traffic to each new build first, and automated checks watch error rates before promoting it to everyone.

A bank’s internal portal

Strict change control requires that every release is described in version-controlled files, reviewed and applied by an automated pipeline. When a bad release is spotted, the team rolls back to the previous revision within minutes.

A media site during breaking news

Traffic jumps tenfold in minutes. Pods are added quickly, spread across machines in several zones, and Pod Disruption Budgets keep enough copies running while the cloud performs routine maintenance.

A startup’s first cluster

A tiny team runs a website and an API as two Deployments with two pods each. Even at this small size, they gain automatic recovery and painless updates without hiring an operations team.

20Best Practices Checklist

Habits that make Deployments dependable.

1

Pin exact image versions

Never rely on a moving label. Precise versions make releases and rollbacks predictable.

2

Always define readiness and liveness probes

They are the safety net that makes rolling updates trustworthy.

3

Set requests and limits

Give the scheduler the information it needs and protect neighbors from greedy pods.

4

Run more than one replica for anything important

And spread them across machines and zones.

5

Tune the update dials to your risk appetite

Zero unavailable pods for critical services, higher surge for faster releases.

6

Keep everything in version control

Change the cluster only through reviewed files applied by pipelines.

7

Practice rollbacks

Know how to return to the last good version quickly before you need to do it in a hurry.

8

Use disruption budgets and graceful shutdown

Give pods time to finish current requests before being stopped.

21Frequently Asked Questions

Q1What is the difference between a Deployment and a ReplicaSet?

A ReplicaSet keeps a set number of identical pods running. A Deployment sits above it and adds update strategies, revision history and rollbacks by managing several ReplicaSets over time.

Q2What is the difference between a Deployment and a Pod?

A pod is a single running unit. A Deployment is the manager that creates the right number of pods, replaces failed ones and handles updates.

Q3Does scaling a Deployment restart its pods?

No. Scaling only adds or removes pods. Existing pods keep running because the pod template has not changed.

Q4What happens if a rollout fails?

The Deployment stops advancing, the old pods keep serving traffic, and after the progress deadline the rollout is marked as failed. You can then inspect the problem or roll back.

Q5Can a Deployment roll back automatically?

Not on its own. Progressive delivery tools and pipelines can add automatic rollback based on health measurements.

Q6How many old versions are kept?

By default, ten old ReplicaSets are kept, controlled by the revision history limit.

Q7Can I run a database with a Deployment?

A single-instance database can technically run, but a StatefulSet with persistent storage, or a managed service, is a much safer choice.

Q8Why did my pods not update after I changed a ConfigMap?

Changing a ConfigMap does not alter the pod template, so no rollout starts by itself. Trigger a rollout restart or include a version marker in the template.

Q9What does it mean that pods are “interchangeable”?

Any pod can serve any request, and losing one does not lose unique data. This is what allows free scaling and replacement.

Q10How many replicas should I run?

For important services, at least two or three across different machines. The right number depends on traffic, cost and how much capacity you can lose during a failure or maintenance.

22Summary and Key Takeaways

A Deployment is the standing order that tells Kubernetes what your stateless application should look like: which container, how many copies and how updates should happen. Behind the scenes, ReplicaSets keep the pod count correct, gradually swap versions during releases and remain available as snapshots for instant rollbacks. Combined with readiness probes, sensible resource settings, spreading rules and version-controlled files, Deployments give teams safe, repeatable releases and applications that recover from failure by themselves.

Key Takeaways

  • Desired state, automatically kept — you declare the pod template and replica count, and the Deployment keeps reality matching it.
  • Deployment, ReplicaSet, Pod — a Deployment manages ReplicaSets, and each ReplicaSet manages the pods of one version.
  • Rolling updates protect users — new pods are added and old ones removed step by step, guided by the surge and unavailable dials.
  • Readiness probes are essential — they decide when a rollout may proceed and when a pod may receive traffic.
  • Rollbacks are quick — old ReplicaSets and revision history let you return to a known good version.
  • Right tool for the job — use Deployments for stateless workloads, and StatefulSets, DaemonSets or Jobs for other needs.
  • Follow the habits — pin image versions, set requests and limits, run several replicas across machines and keep everything in version control.