This website uses cookies. By continuing to browse, you agree to our Privacy Policy.
  • Home
  • Learning Center
  • kubectl apply: Syntax, Examples, and kubectl apply vs. create vs. replace

kubectl apply: Syntax, Examples, and kubectl apply vs. create vs. replace

What Is the kubectl apply Command? 

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

kubectl apply vs. kubectl create vs. kubectl replace: What Is the Difference? 

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.

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.

Common Use Cases for ‘kubectl apply’ 

Creating Resources

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

Updating Resources

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:

# 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:

kubectl apply -f pod.yml

Learn more in our detailed guide to kubectl restart pod

Managing ConfigMaps and Secrets

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

GitOps Workflows

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.

Common Issues With kubectl apply and How to Resolve Them

Incompatible Changes

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.

Conflicting Modifications

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.

Learn more in our detailed guide to kubectl logs 

Namespace Not Specified

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.

Applying a Large Numbers of Resources

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.

Kubernetes Troubleshooting With Komodor

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:

  • Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
  • In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs and etc. All within one pane of glass with easy drill-down options.
  • Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
  • Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.

If you are interested in checking out Komodor, use this link to sign up for a Free Trial.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.