TExcelTAD
Home › Kubernetes › Deployments

Deployments

A Deployment is the standard way to run a stateless application (web servers, APIs, workers). It manages ReplicaSets, which manage Pods:

text
Deployment web
 ├── ReplicaSet web-6d8f9c7b5d   (image nginx:1.27, revision 1, scaled to 0)
 └── ReplicaSet web-7c5ddbdf54   (image nginx:1.28, revision 2, 3 replicas)
      ├── Pod web-7c5ddbdf54-4xk2p
      ├── Pod web-7c5ddbdf54-9qmzt
      └── Pod web-7c5ddbdf54-tl8wd

Why the extra layer? Each version of your Pod template gets its own ReplicaSet. Changing the template (a new image, a new env var) creates a new ReplicaSet and gradually shifts replicas from the old one to the new one. The old ReplicaSets are kept (scaled to 0) so you can roll back.

A complete Deployment

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 3
  revisionHistoryLimit: 5          # old ReplicaSets to keep for rollbacks
  selector:
    matchLabels:
      app: web
  strategy:
    type: RollingUpdate            # or Recreate
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.27
          ports:
            - containerPort: 80
          resources:
            requests: {cpu: 100m, memory: 64Mi}
            limits: {memory: 128Mi}
bash
kubectl apply -f web-deploy.yaml
kubectl get deploy,rs,pods -l app=web
kubectl scale deploy web --replicas=5
kubectl rollout status deploy web

Sample output:

text
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/web   3/3     3            3           40s

NAME                             DESIRED   CURRENT   READY   AGE
replicaset.apps/web-6d8f9c7b5d   3         3         3       40s

NAME                       READY   STATUS    RESTARTS   AGE
pod/web-6d8f9c7b5d-2mxlq   1/1     Running   0          40s
pod/web-6d8f9c7b5d-k8v4z   1/1     Running   0          40s
pod/web-6d8f9c7b5d-wq7rn   1/1     Running   0          40s

Where does the ReplicaSet name come from?

The suffix (6d8f9c7b5d) is the pod-template-hash: a hash of the Pod template. The controller also adds it as a label on the ReplicaSet and its Pods so that ReplicaSets of different versions never select each other's Pods. Same template, same hash; any change, new hash. A model using a stable hash:

python · try it yourself
import hashlib
import json

def template_hash(template):
    data = json.dumps(template, sort_keys=True).encode()
    return hashlib.sha256(data).hexdigest()[:10]

v1 = {"labels": {"app": "web"}, "containers": [{"name": "nginx", "image": "nginx:1.27"}]}
v1_again = {"containers": [{"image": "nginx:1.27", "name": "nginx"}], "labels": {"app": "web"}}
v2 = {"labels": {"app": "web"}, "containers": [{"name": "nginx", "image": "nginx:1.28"}]}

print("v1      ->", "web-" + template_hash(v1))
print("v1 again->", "web-" + template_hash(v1_again))
print("v2      ->", "web-" + template_hash(v2))
v1      -> web-ea17ff3b28
v1 again-> web-ea17ff3b28
v2      -> web-f704f6c777

(Kubernetes uses a different hash function and alphabet, so real suffixes look different, but the principle is identical.)

What triggers a new rollout?

Only changes to spec.template create a new ReplicaSet. Changing spec.replicas just resizes the current one:

python · try it yourself
def classify(old, new):
    changes = []
    if old["template"] != new["template"]:
        changes.append("new ReplicaSet + rolling update")
    if old["replicas"] != new["replicas"]:
        changes.append(f"scale current ReplicaSet {old['replicas']} -> {new['replicas']}")
    return changes or ["no-op"]

base = {"replicas": 3, "template": {"image": "nginx:1.27", "env": {"MODE": "prod"}}}
edits = {
    "scale to 6": {"replicas": 6, "template": base["template"]},
    "new image": {"replicas": 3, "template": {"image": "nginx:1.28", "env": {"MODE": "prod"}}},
    "new env + scale": {"replicas": 4, "template": {"image": "nginx:1.27", "env": {"MODE": "debug"}}},
    "re-apply same file": dict(base),
}
for label, new in edits.items():
    print(f"{label:20} -> {'; '.join(classify(base, new))}")
scale to 6           -> scale current ReplicaSet 3 -> 6
new image            -> new ReplicaSet + rolling update
new env + scale      -> new ReplicaSet + rolling update; scale current ReplicaSet 3 -> 4
re-apply same file   -> no-op

Tip: kubectl rollout restart deploy web restarts all Pods without changing your manifest. It works by setting an annotation with the current time in the Pod template, which counts as a template change.

Strategies

Strategy Behaviour When
RollingUpdate (default) Replace Pods a few at a time; old and new versions run side by side briefly Almost always
Recreate Delete all old Pods, then create the new ones (downtime) App can't run two versions at once (e.g. exclusive DB migrations, single-writer volumes)

The next lesson walks through a rolling update step by step.

Deployment status fields

kubectl get deploy columns come straight from status:

Column Field Meaning
READY readyReplicas/replicas Pods passing readiness
UP-TO-DATE updatedReplicas Pods running the latest template
AVAILABLE availableReplicas Ready for at least minReadySeconds

Test yourself

What does a Deployment create directly?

  1. Pods
  2. ReplicaSets
  3. Nodes
  4. Services

Which change starts a rolling update?

  1. Changing spec.replicas
  2. Changing the container image in spec.template
  3. Adding a label to the Deployment's metadata
  4. Running kubectl get

When is the Recreate strategy appropriate?

  1. Always, it's faster
  2. When two versions of the app must never run at the same time
  3. For zero-downtime releases
  4. Only for DaemonSets