Kubernetes Deployments

A Kubernetes Deployment object provides a means of managing a group of Pod instances, known as replicas. The Deployment tells Kubernetes the type of Pod you want to run and the number of Pod instances. This is known as the desired state.

Kubernetes will actively monitor the number of active Pod replicas and take action to ensure it is the same as the desired state. For example, if your Deployment specifies that there should be three Pod replicas for a microservice, and one of those Pods die, Kubernetes will take corrective action and spin up a new Pod to replace the one that failed.

Defining a Deployment

The Deployment below creates 3 nginx Pod replicas.

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
          imagePullPolicy: Always
  • spec.replicas specifies the number of Pods to create.
  • selector.matchLabels tells Kubernetes that this Deployment will manage Pods with the label app: nginx.
  • template provides a template for the Pod instances that this Deployment will create.
  • template.metadata.labels defines the label that will match this Pod definition to the parent Deployment.
  • spec.containers defines the containers that will run in the Pod instances that are created.

After creating this Deployment object we should see 3 Pods created as follows.

Updating a Deployment

We can update a Deployment to change the state of our Pod replicas.  For example, we can increase the number of replicas from 3 to 5 as follows.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 5
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx
          imagePullPolicy: Always

Remember that we currently have 3 Pod replicas running in the cluster. When we apply this update, Kubernetes will see the updated replicas: 5 and take corrective action to create an additional 2 Pods.

The sample code for these notes is available on Github.