Komodor is a Kubernetes management platform that empowers everyone from Platform engineers to Developers to stop firefighting, simplify operations and proactively improve the health of their workloads and infrastructure.
Proactively detect & remediate issues in your clusters & workloads.
Easily operate & manage K8s clusters at scale.
Reduce costs without compromising on performance.
Empower developers with self-service K8s troubleshooting.
Simplify and accelerate K8s migration for everyone.
Fix things fast with AI-powered root cause analysis.
Explore our K8s guides, e-books and webinars.
Learn about K8s trends & best practices from our experts.
Listen to K8s adoption stories from seasoned industry veterans.
The missing UI for Helm – a simplified way of working with Helm.
Visualize Crossplane resources and speed up troubleshooting.
Validate, clean & secure your K8s YAMLs.
Navigate the community-driven K8s ecosystem map.
Kubernetes 101: A comprehensive guide
Expert tips for debugging Kubernetes
Tools and best practices
Kubernetes monitoring best practices
Understand Kubernetes & Container exit codes in simple terms
Exploring the building blocks of Kubernetes
Cost factors, challenges and solutions
Kubectl commands at your fingertips
Understanding K8s versions & getting the latest version
Rancher overview, tutorial and alternatives
Kubernetes management tools: Lens vs alternatives
Troubleshooting and fixing 5xx server errors
Solving common Git errors and issues
Who we are, and our promise for the future of K8s.
Have a question for us? Write us.
Come aboard the K8s ship – we’re hiring!
Hear’s what they’re saying about Komodor in the news.
The kubectl apply command is a tool provided by the Kubernetes command-line interface (CLI) that allows you to configure applications. It is used to create or update resources in a Kubernetes cluster using configuration files. This is different from the kubectl create and kubectl replace commands, which we’ll explore later.
kubectl apply
kubectl create
kubectl replace
kubectl apply provides a declarative way of deploying resources on a cluster using YAML manifest files. It works by determining and applying the difference between the current state of a resource and the desired state described in the configuration file. The user does not need to understand the current state of the Kubernetes cluster, only specify the desired behavior.
The kubectl apply command applies a configuration to a resource by file name or stdin. The resource name must be specified. If the resource doesn’t exist yet, it will be created. If the resource already exists, the command won’t error. You can also use kubectl apply to update an object in Kubernetes if you only have a partial object with specific settings to update.This is part of a series of articles about kubectl cheat sheet.
Understanding the difference between kubectl apply, kubectl create, and kubectl replace is crucial for managing your Kubernetes resources effectively.
kubectl create is an imperative command that creates a new resource. However, it fails if the resource already exists. kubectl replace is also imperative and replaces the existing resource with a new one. It creates a new resource if it doesn’t exist yet.
In contrast, kubectl apply is a declarative command that manages applications through files defining the resource. It creates the resource if it doesn’t exist, and if it does, the resource is automatically updated. This is why kubectl apply is often preferred over kubectl create and kubectl replace as it allows management of resources in a more controlled and predictable manner.
The syntax for the kubectl apply command is quite straightforward. The command takes a file or directory of files and sends them to the Kubernetes API server to be processed. The basic syntax is as follows:
kubectl apply -f FILENAME
In this syntax, FILENAME is the name of the file that contains the configuration you want to apply. The -f flag specifies that the following argument is a filename.
FILENAME
-f
Here’s an example:
kubectl apply -f my-app-config.yml
In this example, my-app-config.yml is a YAML file that contains the configuration for a Kubernetes application. The kubectl apply command sends this configuration to the Kubernetes API server, which then creates or updates the resources described in the file.
my-app-config.yml
Itiel Shwartz
Co-Founder & CTO
In my experience, here are tips that can help you better utilize kubectl apply:
kubectl diff
Use kubectl diff -f <filename> to preview changes before applying them. This command helps identify potential issues and understand the impact of changes, ensuring smoother updates.
kubectl diff -f <filename>
Store configuration files in a version-controlled repository, and use branches to manage different environments (e.g., development, staging, production). This practice enhances traceability and rollback capabilities.
Use Kustomize, which is integrated with kubectl, to manage overlays and customizations for different environments. This avoids duplicating configuration files and simplifies managing complex deployments.
kubectl
kubectl apply --server-side
Server-side apply offers better performance and conflict resolution. It allows multiple actors to manage resources concurrently without overwriting each other’s changes, improving collaboration.
Integrate kubectl apply in your CI/CD pipeline to automatically deploy changes from your repository. Tools like Jenkins, GitLab CI, or GitHub Actions can streamline deployments and ensure consistency.
One of the most common use cases for the kubectl apply command is creating resources. Unlike kubectl create, kubectl apply allows you to create resources using configuration files rather than command-line arguments. This makes it easier to manage complex applications and enables you to track changes to your application configuration over time.
Here’s an example of how to create resources using kubectl apply. Consider a configuration file, pod.yml, that describes a simple pod running a nginx server.
pod.yml
# pod.yml apiVersion: v1 kind: Pod metadata: name: nginx-pod labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80
You can create the pod with the following command:
kubectl apply -f pod.yml
kubectl apply is also commonly used to update existing resources. It compares the desired state specified in the configuration file with the current state of the resource in the cluster and makes the necessary changes to bring the resource into the desired state. This is especially useful when managing complex applications with many interdependent resources.
Let’s assume that you want to update the nginx-pod to use a different image version. You would first modify your configuration file:
nginx-pod
# pod.yml apiVersion: v1 kind: Pod metadata: name: nginx-pod labels: app: nginx spec: containers: - name: nginx image: nginx:1.18.0 ports: - containerPort: 80
Then you apply the updated configuration:
Learn more in our detailed guide to kubectl restart pod
Another common use case for kubectl apply is managing ConfigMaps and Secrets. These are special types of Kubernetes resources that allow you to store and manage sensitive information, such as passwords and API keys, separately from your application code. kubectl apply makes it easy to create, update, and delete ConfigMaps and Secrets without affecting the rest of your application.
Here’s how you can create a ConfigMap using kubectl apply. First, create a file called config-map.yml:
config-map.yml
# config-map.yml apiVersion: v1 kind: ConfigMap metadata: name: game-config data: game.properties: | enemies=aliens lives=3
Then apply the ConfigMap with the following command:
kubectl apply -f config-map.yml
After the ConfigMap is created, you can use it in a Pod configuration. The following example shows how to mount the ConfigMap to a Pod:
# pod-configmap.yml apiVersion: v1 kind: Pod metadata: name: game-pod spec: containers: - name: game image: game-image:1.0 volumeMounts: - name: config-volume mountPath: /game/config volumes: - name: config-volume configMap: # Provide the name of the ConfigMap you want to mount. name: game-config
In this example, the ConfigMap game-config is mounted to the Pod game-pod under the path /game/config. You can apply this Pod configuration by running:
kubectl apply -f pod-configmap.yml
Now, your application inside the Pod can access the configuration data stored in the ConfigMap from the files located in the directory /game/config.
/game/config
Finally, kubectl apply is a crucial tool in GitOps workflows. GitOps is a way of implementing Continuous Deployment for cloud-native applications. It uses Git as a single source of truth for declarative infrastructure and applications. With GitOps, kubectl apply can be used to automatically apply the desired state of your Kubernetes resources stored in a Git repository whenever a new commit is made.
In a GitOps workflow, you would usually have a Continuous Integration/Continuous Deployment (CI/CD) pipeline setup. Whenever you push changes to your Git repository, your CI/CD pipeline is triggered and it runs the kubectl apply command. Here’s a simple example using GitLab’s CI/CD:
# .gitlab-ci.yml stages: - deploy deploy_job: stage: deploy image: dtzar/helm-kubectl:3.2.4 script: - kubectl apply -f deployment.yml only: - master
In this example, when changes are pushed to the master branch, the CI/CD pipeline is triggered, and the kubectl apply -f deployment.yml command is run to update the application on the Kubernetes cluster.
kubectl apply -f deployment.yml
One common issue that Kubernetes users often face when using the kubectl apply command is dealing with incompatible changes. This occurs when the live configuration of a Kubernetes cluster doesn’t match the configuration file you’re trying to apply.
When such a situation arises, it’s important to understand what changes are causing the incompatibility. This can be done by using the kubectl diff command to compare the current live configuration with the configuration file. Once identified, the incompatible changes can be resolved either by modifying the configuration file or by manually updating the live configuration.
Another issue that can arise when using the kubectl apply command is conflicting modifications. This happens when multiple users or automated processes are modifying the same resources in a Kubernetes cluster simultaneously. The best way to resolve this is to review logs, understand what changes were previously made, and update your configuration accordingly.
As a last resort, you can use the kubectl apply --force command. This will force Kubernetes to apply the changes, even if there are conflicts. However, it’s important to understand the potential risks associated with using the --force option as it can cause undesirable changes to the live configuration.
kubectl apply --force
--force
Learn more in our detailed guide to kubectl logs
A common mistake, especially for those new to Kubernetes, is forgetting to specify the namespace when using the kubectl apply command. This can cause confusion and errors, as Kubernetes will apply the configuration to the default namespace.
To avoid this issue, always remember to specify the namespace when using the kubectl apply command. You can do this by adding the -n or --namespace flag followed by the name of the namespace. If you frequently work with a specific namespace, consider setting it as your default namespace to avoid forgetting to specify it in the future.
--namespace
When working with large Kubernetes clusters, you may need to apply changes to a large number of resources simultaneously. While the kubectl apply command is designed to handle this, it can sometimes become slow or unresponsive when dealing with a large number of resources.
If you encounter this issue, consider breaking down your changes into smaller, more manageable chunks. You can do this by splitting your configuration files into smaller files or by using the kubectl apply command with the --chunk-size flag to specify the number of resources to be modified in each operation.
--chunk-size
Kubernetes is a complex system, and often, something will go wrong, simply because it can. In situations like this, you’ll likely begin the troubleshooting process by reverting to some of the above kubectl commands to try and determine the root cause. This process, however, can often run out of hand and turn into a stressful, ineffective, and time-consuming task.
This is the reason why we created Komodor, a tool that helps dev and ops teams stop wasting their precious time looking for needles in (hay)stacks every time things go wrong.
Acting as a single source of truth (SSOT) for all of your k8s troubleshooting needs, Komodor offers:
If you are interested in checking out Komodor, use this link to sign up for a Free Trial.
Share:
How useful was this post?
Click on a star to rate it!
Average rating 4.5 / 5. Vote count: 8
No votes so far! Be the first to rate this post.
and start using Komodor in seconds!