How to Use the Kubectl Apply Command

The kubectl apply command is used to create or update Kubernetes resources based on the configuration files provided. It is a convenient way to manage your Kubernetes resources and ensure that they match the desired state. Here’s how you can use the kubectl apply command:

  1. Ensure that you have kubectl installed and properly configured to connect to your Kubernetes cluster.

  2. Create or obtain the configuration file(s) that define the desired state of your Kubernetes resources. These files can be in YAML or JSON format and should include the necessary resource definitions.

  3. Open your terminal or command prompt and run the following command:

    kubectl apply -f {{path/to/config/file}}
    

    Replace {{path/to/config/file}} with the actual path to your configuration file. If you have multiple configuration files, you can specify a directory or use wildcards to apply all files in a directory.

  4. The kubectl apply command will read the configuration file(s) and create or update the corresponding Kubernetes resources in your cluster.

    • If the resources specified in the configuration file(s) do not exist, they will be created.
    • If the resources already exist, kubectl apply will update them to match the desired state defined in the configuration file(s). It will perform a “declarative” update, meaning it will make the necessary changes to bring the resources in line with the desired state.
  5. After running the kubectl apply command, you will see the output indicating the resources that have been created or updated.

    For example:

    deployment.apps/my-deployment created
    service/my-service created
    

    This output confirms that the deployment and service resources have been created.

  6. You can verify the status of your resources by running kubectl get commands. For example:

    kubectl get pods
    kubectl get deployments
    kubectl get services
    

    These commands will display the current status of the pods, deployments, and services in your cluster.

The kubectl apply command is a powerful tool for managing Kubernetes resources. It allows you to easily create or update resources based on the desired state defined in configuration files. By using kubectl apply, you can ensure that your resources are always in sync with your desired configuration.

Note: It’s important to carefully review your configuration files before applying them to your cluster to avoid unintended changes or conflicts with existing resources.