The key difference between ‘kubectl apply’ and ‘kubectl create’ is that the kubectl apply is suitable for managing resources in a declarative manner, with the ability to create and update resources, while kubectl create used for imperatively creating resources.
The kubectl is a command-line tool for interacting with a Kubernetes cluster, allowing you to create, update, and manage various Kubernetes resources.
Those are two different approaches:
Imperative Management
The kubectl create
is what we call Imperative Management. In 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.
Declarative Management
The 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.
Both kubectl apply and kubectl create commands are used for creating resources, but they have some key differences in their behavior and use cases.
kubectl apply
- Idempotent: The
kubectl apply
is an idempotent operation, meaning that you can run it multiple times, producing the same result as if executed once. It ensures that the resource’s configuration matches the one in the file or from standard input by creating or updating the resource. - Declarative approach: The
kubectl apply
follows a declarative approach, where you describe the desired state of your resources in a YAML or JSON file, and the command ensures that the cluster’s state matches the described state. - Updates: This command can be used to create and update new resources. When you make changes to the configuration file and run
kubectl apply
again, it will update the resource in the cluster. - Tracking: The
kubectl apply
uses annotations to keep track of the configuration applied to a resource. This allows it to calculate the differences between the applied configuration and the current cluster state, applying the necessary changes. - Using ‘kubectl apply’ to manage resources in production environments is generally recommended, as it provides a more consistent and predictable approach to resource management.
kubectl create
- Non-idempotent: The
kubectl create
is a non-idempotent operation. Running it multiple times with the same configuration will result in errors, as it will try to create existing resources. - Imperative approach: The
kubectl create
follows an imperative approach, where you explicitly tell the command what resource to create. - Creation only: This command is used solely for creating new resources. If you need to update a resource, you would have to use a separate command like
kubectl replace
orkubectl patch
. - No tracking: The
kubectl create
It does not track the applied configuration, so it cannot calculate the differences between it and the current cluster state.
That’s it.