What I understood by the documentation is that kubectl apply = kubectl create + kubectl replace. Reference
My understanding is that if I want create new k8s resource in the cluster I should use kubectl create operation. Now If I want to update something in a live k8s resources I should use kubectl replace operation.
If I want to do both operations (create a new k8s resource as well as update the live k8s resources ) then I should use kubectl apply operation
My questions are Why are there three operations for doing the same task in a cluster? What are the use cases for these operations? How do they differ from each other under the hood?
At the moment I am using kubectl create operation for creating new resources in the cluster. Thanks
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.
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).
Just to give a more straight forward answer, from my understanding:
apply
- makes incremental changes create
- overwrites all changes
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.
The explanation below from the official documentation helped me understand kubectl apply
.
This command will compare the version of the configuration that you’re pushing with the previous version and apply the changes you’ve made, without overwriting any automated changes to properties you haven’t specified.
kubectl create
on the other hand will create (should be non-existing) resources.
来源:https://stackoverflow.com/questions/47369351/kubectl-apply-vs-kubectl-create