Both kubectl apply and kubectl create are commands used to create resources in a Kubernetes cluster. So, it’s natural to wonder why there are two commands that do similar things. While you can use both commands to create resources, they have different purposes and distinct behaviours. This article discusses how kubectl apply and kubectl create are different and when to use each command.
Table of contents
The kubectl create command
The kubectl create command is used to create new resources in the cluster. It takes the manifest definition files (usually JSON or Yaml) and creates the specified resources exactly as defined. The create command will not proceed if the resource defined already exists, even if there are changes in the manifest file.
Example:
kubectl create -f deployment.yaml
The above command will create the resource defined in the deployment.yaml file. If the resource in the deployment.yaml already exists, the create command will throw an error.
The kubectl apply command
The kubectl apply command is used for declarative management of Kubernetes resources. It allows you to create or update new resources based on the configuration file. In other words, if the resource defined in your configuration file does not exist, the command will create it. Likewise, if the resource specified in the config file already exists, the command will update the resource with the config defined in the YAML.
Example:
kubectl apply -f deployment.yaml
This command will create the deployment if it doesn’t exist or update the existing deployment to match the configuration in deployment.yaml.
Comparing the two commands
| Feature | kubectl create | kubectl apply |
|---|---|---|
| Primary Function | Create new resources | Create or update resources |
| Behaviour on Existing Resources | Behaviour on Existing Resources | Updates the resource if it exists |
| Idempotency | No | Yes. Meaning, you can run the command multiple times It will ensure the desired state as defined in the configuration file. |
| Use Case | Static resource creation | Declarative resource management |
| Handling Changes | N/A | Applies changes incrementally |
When to use each of the commands
When choosing between kubectl create and kubectl apply, consider the following:
- Initial Creation: For initial resource creation where updates are not anticipated,
kubectl createis straightforward. - Ongoing Management: For resources that require frequent updates or are part of a CI/CD pipeline,
kubectl applyoffers more flexibility and safety. - Configuration as Code: Adopting
kubectl applyaligns well with the GitOps model, where configurations are stored in version control and applied declaratively.
Also Read: Which Kubernetes apiVersion Should You Use?
Conclusion
Use kubectl create for simple, one-time resource creation. Similarly, for managing resources declaratively and ensuring your cluster remains desired as defined by your configuration files, use kubectl apply.
