How to Create a Kubernetes Deployment: A Step-by-Step Guide
A Kubernetes Deployment is the most common way to run stateless applications in a cluster. It manages a set of identical Pods, handles rolling updates, and provides self-healing capabilities. In this tutorial, you will learn how to create a Deployment from scratch using the imperative and declarative approaches.
Before you begin, ensure you have a running Kubernetes cluster (e.g., minikube or a cloud-based cluster) and kubectl installed. The following steps assume you are using the command line.
1. Define the Deployment Manifest
Every Deployment starts with a YAML file that defines its desired state. Create a file named nginx-deployment.yaml with this content:
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.21
ports:
- containerPort: 80
Key Fields Explained
- replicas: Number of Pod replicas to run.
- selector: Defines which Pods the Deployment manages by labels.
- template: The Pod specification used to create new Pods.
2. Apply the Deployment
Use kubectl apply to create the Deployment in your cluster:
kubectl apply -f nginx-deployment.yaml
This command sends the manifest to the Kubernetes API server, which then creates the Deployment and its associated Pods.
3. Verify the Deployment
Check the status of your Deployment and its Pods:
kubectl get deployments
kubectl get pods
4. Update or Scale the Deployment
To change the number of replicas, edit the YAML file and re-apply, or use the imperative command:
kubectl scale deployment nginx-deployment --replicas=5
For a rolling update (e.g., change the image), modify the image field in the YAML and run kubectl apply again.
Conclusion: Creating a Kubernetes Deployment is straightforward once you understand the YAML structure. Use the declarative approach with a manifest file to keep your infrastructure as code, and leverage kubectl commands to manage your application lifecycle. Experiment with scaling and rolling updates to see Kubernetes’ self-healing in action.