Deployments and ReplicaSets
Bare Pods have no self-healing: if a Pod's node dies, that Pod is gone for good. A Deployment is the standard way to run and manage Pods in practice, it describes a desired state and Kubernetes continuously reconciles reality to match it.
Declaring a Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: myregistry/web:1.4.0
ports:
- containerPort: 8080
replicas: 3declares you always want 3 copies of this Pod running.selector/template.metadata.labelsmust match, this is how the Deployment knows which Pods belong to it.templateis effectively a Pod spec, the Deployment stamps out Pods from this template.
ReplicaSets: the mechanism underneath
A Deployment doesn't manage Pods directly, it manages a ReplicaSet, which is the thing that actually watches the Pod count and creates/deletes Pods to match replicas. You'll almost never create a ReplicaSet by hand, but understanding it explains what's happening when you list resources:
kubectl get deployments
kubectl get replicasets
kubectl get pods
Each layer exists for a reason: the Deployment adds rollout history and rolling updates on top of what a plain ReplicaSet can do.
Rolling updates
Change the image tag and re-apply, and the Deployment performs a rolling update by default: it spins up new Pods with the new version, waits for them to become healthy, then terminates old Pods, a few at a time, so the service never has zero healthy replicas.
kubectl set image deployment/web web=myregistry/web:1.5.0
kubectl rollout status deployment/web
kubectl rollout undo deployment/web # roll back if something's wrong
TIP
kubectl rollout undo is your emergency brake, it re-applies the previous ReplicaSet's Pod template immediately, no need to remember or re-type the old image tag.