G
GuideDevOps
Lesson 5 of 17

ReplicaSets & Deployments

Part of the Kubernetes tutorial series.

In production, you never create individual Pods. Instead, you create a Deployment. A Deployment manages a set of identical Pods and ensures the correct number are running at all times.

1. Creating a Deployment

deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

Apply the Deployment

Action:

kubectl apply -f deployment.yaml

Result:

deployment.apps/nginx-deployment created

2. Scaling Your Application

Need more traffic? Scaling is as simple as changing one number.

Scale to 10 Replicas

Action:

kubectl scale deployment nginx-deployment --replicas=5

Result:

deployment.apps/nginx-deployment scaled
 
# Check status
kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-75675f5897-4qsqj   1/1     Running   0          2m
nginx-deployment-75675f5897-7r7rt   1/1     Running   0          10s
nginx-deployment-75675f5897-8r8rt   1/1     Running   0          10s
...

3. Rolling Updates

One of the best features of a Deployment is the ability to update your application without downtime.

Update the Image Version

Action:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1

Result:

deployment.apps/nginx-deployment image updated
 
# Watch the rollout
kubectl rollout status deployment/nginx-deployment

Result:

Waiting for deployment "nginx-deployment" rollout to finish: 1 out of 5 new replicas have been updated...
Waiting for deployment "nginx-deployment" rollout to finish: 2 out of 5 new replicas have been updated...
...
deployment "nginx-deployment" successfully rolled out

4. Rollbacks

If your update introduced a bug, you can revert it instantly.

Undo the Rollout

Action:

kubectl rollout undo deployment/nginx-deployment

Result:

deployment.apps/nginx-deployment rolled back

Summary

  • Deployments manage ReplicaSets, which in turn manage Pods.
  • scale: Changes the number of running instances.
  • Rolling Update: Replaces old Pods with new ones gradually.
  • Rollback: Instantly revert to a previous stable version.