What I understood by the documentation is that:
One for the finest way to understand the difference for beginner.
Ref : https://www.digitalocean.com/community/tutorials/imperative-vs-declarative-kubernetes-management-a-digitalocean-comic
Those are two different approaches:
kubectl create
is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.
kubectl apply
is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale
) are "maintained" even if you apply
other changes to the object.
You can read more about imperative and declarative management in the Kubernetes Object Management documentation.
Just to give a more straight forward answer, from my understanding:
apply
- makes incremental changes to an existing object
create
- creates a whole new object (previously non-existing / deleted)
Taking this from a DigitalOcean article which was linked by Kubernetes website:
We use apply instead of create here so that in the future we can incrementally apply changes to the Ingress Controller objects instead of completely overwriting them.
┌─────────┬───────────────────────┬────────────────────────┐
│ command │ object does not exist │ object already exists │
├─────────┼───────────────────────┼────────────────────────┤
│ create │ create new object │ ERROR │
│ │ │ │
│ apply │ create new object │ configure object │
│ │ (needs complete spec) │ (accepts partial spec) │
│ │ │ │
│ replace │ ERROR │ delete object │
│ │ │ create new object │
└─────────┴───────────────────────┴────────────────────────┘
kubectl create can work with one object configuration file at a time. This is also known as imperative management
kubectl create -f filename|url
kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/
Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/
When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.
What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true
and -o yaml
options:
kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -
The command above will not raise an error if the resource already exists (and will update the resource if needed).
This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).