In this lesson, we will learn how to deploy applications on Kubernetes using YAML files and the kubectl command-line tool. Understanding how to create and manage deployments is essential for running applications in a Kubernetes cluster.
A Deployment in Kubernetes is a resource object that provides declarative updates to applications. It allows you to describe an application’s desired state, such as which images to use for the app, the number of replicas, and the update strategy.
Deployment).name and labels.To create a Deployment, you need to write a YAML file that defines the Deployment configuration. Below is an example YAML file for a simple web application.
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-web-app
spec:
replicas: 3
selector:
matchLabels:
app: my-web-app
template:
metadata:
labels:
app: my-web-app
spec:
containers:
- name: web
image: nginx:latest
ports:
- containerPort: 80
replicas: 3: This specifies that we want three instances of the application running.selector: This is used to identify the Pods that belong to this Deployment.template: This defines the Pod template that will be used to create the Pods.Once you have created the YAML file (let's say you saved it as deployment.yaml), you can apply it using the kubectl command:
kubectl apply -f deployment.yaml
This command tells Kubernetes to create the Deployment as defined in the YAML file.
You can check the status of your Deployment with the following command:
kubectl get deployments
To see the Pods created by the Deployment, use:
kubectl get pods
Updating a Deployment is as simple as modifying the YAML file and applying it again. For example, if you want to update the image version, change the image line in your YAML file:
image: nginx:1.21
Then apply the changes:
kubectl apply -f deployment.yaml
Kubernetes supports rolling updates, which means that updates can be applied without downtime. You can control the update strategy by adding the following to your spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
Best Practice: Always use versioned images (e.g.,
nginx:1.21instead ofnginx:latest) to avoid unexpected changes. Common Mistake: Forgetting to set theselectorcorrectly can lead to Pods not being managed by the Deployment.
kubectl.node:14 and set replicas to 2.kubectl and check the status of the Pods.node:16 and apply the changes. Verify that the update was successful.kubectl.