How to Create Kubernetes Deployment Using YAML
To create a Kubernetes deployment using
yaml, define a Deployment resource with apiVersion, kind, metadata, and spec sections. Then apply it with kubectl apply -f filename.yaml to deploy your application.Syntax
A Kubernetes deployment YAML file has these main parts:
- apiVersion: Specifies the Kubernetes API version, usually
apps/v1. - kind: The resource type, here it is
Deployment. - metadata: Contains the deployment name and labels.
- spec: Defines the desired state, including
replicas,selector, andtemplatefor pods.
yaml
apiVersion: apps/v1 kind: Deployment metadata: name: my-deployment spec: replicas: 3 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: containers: - name: my-container image: my-image:latest ports: - containerPort: 80
Example
This example creates a deployment named nginx-deployment with 2 replicas running the nginx:1.21.6 image. It shows how to define labels, replicas, and container details.
yaml
apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.21.6 ports: - containerPort: 80
Output
deployment.apps/nginx-deployment created
Common Pitfalls
Common mistakes when creating deployments with YAML include:
- Missing or incorrect
selector.matchLabelsthat must matchtemplate.metadata.labels. - Forgetting to specify
replicas, which defaults to 1 but might not be intended. - Using an invalid or missing container
image. - Indentation errors in YAML causing parsing failures.
yaml
apiVersion: apps/v1 kind: Deployment metadata: name: bad-deployment spec: replicas: 2 selector: matchLabels: app: wrong-label # Does not match template labels template: metadata: labels: app: right-label spec: containers: - name: app image: nginx:latest ports: - containerPort: 80 # Corrected selector to match template labels apiVersion: apps/v1 kind: Deployment metadata: name: good-deployment spec: replicas: 2 selector: matchLabels: app: right-label template: metadata: labels: app: right-label spec: containers: - name: app image: nginx:latest ports: - containerPort: 80
Quick Reference
Remember these tips when writing deployment YAML:
- apiVersion: Use
apps/v1for deployments. - selector.matchLabels: Must exactly match
template.metadata.labels. - replicas: Number of pod copies to run.
- containers: Define container name, image, and ports.
- Apply with
kubectl apply -f yourfile.yaml.
Key Takeaways
Define a deployment YAML with apiVersion, kind, metadata, and spec sections.
Ensure selector.matchLabels matches template.metadata.labels exactly.
Specify the number of replicas to control pod count.
Use kubectl apply -f filename.yaml to create or update the deployment.
Check YAML indentation carefully to avoid errors.