kubectl apply: Managing Kubernetes Resources

The kubectl apply command is a fundamental tool for creating, updating, and deleting Kubernetes resources from manifest files (YAML or JSON). It’s declarative, meaning you define the desired state of your resources in files, and kubectl apply makes the necessary changes to reach that state.

Applying Kustomization Overlays

Kustomize is a Kubernetes-native tool that helps you customize raw, template-free YAML files for multiple purposes, leaving the original YAML intact. When working with Kustomization, you can apply your configurations using the -k flag.

To apply resources defined in a kustomization.yaml file (or a directory containing it):

# Navigate to the directory containing kustomization.yaml
# Then run:
kubectl apply -k .

This command will apply all resources generated by the kustomization.yaml in the current directory.

Applying Individual YAML Manifests

The most common way to manage resources is by directly applying a YAML file.

To apply a single YAML manifest:

# Example: apply a single deployment file
kubectl apply -f my-deployment.yaml

Applying Multiple YAML Manifests or a Directory

You can apply multiple files at once, or even all YAML files within a directory:

# Apply multiple specific files
kubectl apply -f deployment.yaml -f service.yaml
 
# Apply all .yaml and .json files in a directory
kubectl apply -f ./my-manifests-directory/

Dry Run for Validation

Before applying changes, it’s often useful to perform a “dry run” to see what changes would be made without actually modifying your cluster.

# Perform a dry run to validate the changes
kubectl apply -f my-deployment.yaml --dry-run=client -o yaml

This command will output the manifest that would be applied, allowing you to inspect it.