kubectl apply vs kubectl create?

KubernetesKubectl

Kubernetes Problem Overview


What I understood by the documentation is that:

  • kubectl create
    
    Creates a new k8s resource in the cluster
  • kubectl replace
    
    Updates a resource in the live cluster
  • kubectl apply
    
    If I want to do create + replace (Reference)

My questions are

  1. Why are there three operations for doing the same task in a cluster?
  2. What are the use cases for these operations?
  3. How do they differ from each other under the hood?

Kubernetes Solutions


Solution 1 - Kubernetes

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.

Solution 2 - Kubernetes

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

Solution 3 - Kubernetes

One of the finest ways to understand the difference between imperative and declarative patterns 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.

Solution 4 - Kubernetes

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.

Solution 5 - Kubernetes

┌─────────┬───────────────────────┬────────────────────────┐
│ command │ object does not exist │ object already exists  │
├─────────┼───────────────────────┼────────────────────────┤
│ create  │ create new objectERROR         │ 
│         │                       │                        │
│ apply   │ create new object     │ configure object       │
│         │ (needs complete spec) │ (accepts partial spec) │
│         │                       │                        │
│ replace │         ERROR         │ delete object          │
│         │                       │ create new object      │
└─────────┴───────────────────────┴────────────────────────┘

Solution 6 - Kubernetes

These are imperative commands :

kubectl run = kubectl create deployment

Advantages:
  • Simple, easy to learn and easy to remember.
  • Require only a single step to make changes to the cluster.
Disadvantages:
  • Do not integrate with change review processes.
  • Do not provide an audit trail associated with changes.
  • Do not provide a source of records except for what is live.
  • Do not provide a template for creating new objects.

These are imperative object config:

kubectl create -f your-object-config.yaml

kubectl delete -f your-object-config.yaml

kubectl replace -f your-object-config.yaml

Advantages compared to imperative commands:
  • Can be stored in a source control system such as Git.
  • Can integrate with processes such as reviewing changes before push and audit trails.
  • Provides a template for creating new objects.
Disadvantages compared to imperative commands:
  • Requires basic understanding of the object schema.
  • Requires the additional step of writing a YAML file.
Advantages compared to declarative object config:
  • Simpler and easier to understand.
  • More mature after Kubernetes version 1.5.
Disadvantages compared to declarative object configuration:
  • Works best on files, not directories.
  • Updates to live objects must be reflected in configuration files, or they will be lost during the next replacement.

These are declarative object config

kubectl diff -f configs/

kubectl apply -f configs/

Advantages compared to imperative object config:
  • Changes made directly to live objects are retained, even if they are not merged back into the configuration files.
  • Better support for operating on directories and automatically detecting operation types (create, patch, delete) per-object.
Disadvantages compared to imperative object configuration:
  • Harder to debug and understand results when they are unexpected.
  • Partial updates using diffs create complex merge and patch operations.

Solution 7 - Kubernetes

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.

Solution 8 - Kubernetes

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/

Solution 9 - Kubernetes

We love Kubernetes is because once we give them what we want it goes on to figure out how to achieve it without our any involvement.

"create" is like playing GOD by taking things into our own hands. It is good for local debugging when you only want to work with the POD and not care abt Deployment/Replication Controller.

"apply" is playing by the rules. "apply" is like a master tool that helps you create and modify and requires nothing from you to manage the pods.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuresh VishnoiView Question on Stackoverflow
Solution 1 - KubernetesAra PulidoView Answer on Stackoverflow
Solution 2 - KubernetesSébastien DanView Answer on Stackoverflow
Solution 3 - Kubernetesdahiya_boyView Answer on Stackoverflow
Solution 4 - KubernetesUser9123View Answer on Stackoverflow
Solution 5 - KubernetestimgebView Answer on Stackoverflow
Solution 6 - KubernetesZoe The ParanoidView Answer on Stackoverflow
Solution 7 - Kubernetesf01View Answer on Stackoverflow
Solution 8 - KubernetesNoman KhanView Answer on Stackoverflow
Solution 9 - KubernetesAnkur KothariView Answer on Stackoverflow