kubectl apply vs kubectl create? kubectl apply vs kubectl create? kubernetes kubernetes

kubectl apply vs kubectl create?


Those are two different approaches:

Imperative Management

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.

Declarative Management

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.

In laymans They do different things. If the resource exists, kubectl create will error out and kubectl apply will not error out.


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).


One for the finest way to understand the difference for beginner.


enter image description here


Ref : https://www.digitalocean.com/community/tutorials/imperative-vs-declarative-kubernetes-management-a-digitalocean-comic


EDIT

There is error is the example mentioned in image. Please refer comments for better understanding.

You can also refer below example.

Imperative :

  • take a pan.
  • turn on stove.
  • add water, sugar, coffee power, milk in pan
  • wait till the preparation of coffee
  • serve coffee in cup.

Declarative :

  • Tell the waiter you need a cup of coffee. He servers you coffee.

From K8s perspective:

Imperative : You have to manage different resources like pods, service, replica sets, etc by your own.

Declarative : K8 will take care of all the resources, all you need have to specify what is your actual requirement.