kubectl apply
- Docker & Kubernetes course
- Intermediate
- Lesson 16/82
- 4 min
Learn to apply a YAML file with kubectl apply.
kubectl apply
kubectl apply -f creates the objects in the file or updates existing ones to match the file. All YAML files in a folder, or even a URL, can be applied:
kubectl apply -f web.yaml
kubectl apply -f k8s/ # all files in the folder
kubectl apply -f https://example.com/kurulum.yamlSeveral objects can be written in one YAML file with the --- separator.
See the difference first
Before applying a change, kubectl diff shows the difference between what's in the cluster and the file; --dry-run=server validates the request but doesn't save it. Instead of writing an object's YAML skeleton from scratch, you can generate it with --dry-run=client -o yaml:
kubectl diff -f web.yaml
kubectl apply -f web.yaml --dry-run=server
kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > web.yamlPractice Generate, check, apply
Write three commands: generate the YAML of a web deployment with the nginx:1.27 image without creating it and write it to web.yaml; show the difference for web.yaml; apply the file.
Starter code
# buraya yazSample solution
kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > web.yaml
kubectl diff -f web.yaml
kubectl apply -f web.yamlExpected output
+ replicas: 1 + selector: + matchLabels: + app: web deployment.apps/web created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between kubectl create -f and kubectl apply -f?
- They are the same
- apply only deletes
- create accepts folders, apply doesn't
- create errors if the object exists; apply updates it Correct answer
Explanation: apply can be run again and again (idempotent).
2 Show the difference before applying the change.
kubectl ____ -f web.yaml
kubectl diff -f web.yaml
Explanation: diff shows the change apply would make.
3 Match.
| Term | Meaning |
|---|---|
apply -f |
Create or update |
create -f |
Create only |
diff -f |
Show the difference |
--dry-run=client -o yaml |
Generate a skeleton |