Kubernetes CLI

kubectl cheatsheet — get pods, deploy apps, exec into containers, check logs. kubectl get pods -n ns, kubectl exec -it, kubectl apply -f, kubectl rollout. Full K8s CLI.

9 min read

kubectl

What it is

The command-line interface for interacting with Kubernetes clusters, used for deploying applications, inspecting and managing cluster resources, and viewing logs.

Installation

Linux

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
rm kubectl

macOS

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
rm kubectl

For Apple Silicon Macs, replace amd64 with arm64.

Windows

Download the latest release from Kubernetes release page. Add the downloaded executable to your system’s PATH.

Configuration

To configure kubectl to connect to a cluster, you need a kubeconfig file. This is typically generated by your cluster administrator or cloud provider.

# Copy the kubeconfig file to the default location
mkdir -p $HOME/.kube
cp your-kubeconfig-file $HOME/.kube/config

# Set KUBECONFIG environment variable (alternative)
export KUBECONFIG=/path/to/your/kubeconfig

Core Concepts

  • Pods: The smallest deployable units in Kubernetes. A Pod represents a single instance of a running process in your cluster and can contain one or more containers.
  • Deployments: Manages stateless applications. It describes the desired state for your application and the Deployment controller ensures that the current state matches the desired state.
  • Services: An abstraction that defines a logical set of Pods and a policy by which to access them. Services provide stable network endpoints for your applications.
  • Namespaces: Provide a mechanism for isolating groups of resources within a single cluster.
  • ConfigMaps and Secrets: Store configuration data and sensitive information, respectively, decoupling it from application code.

Commands / Usage

Cluster Information

  • Get cluster version

    kubectl version
    

    Displays the client and server versions of kubectl.

  • Get cluster info

    kubectl cluster-info
    

    Prints the addresses of the Kubernetes control plane and CoreDNS.

  • List available nodes

    kubectl get nodes
    

    Shows all nodes in the cluster with their status.

  • Describe a node

    kubectl describe node worker-node-1
    

    Provides detailed information about a specific node, including its capacity, allocated resources, and events.

Resource Management

  • List resources in the default namespace

    kubectl get pods
    kubectl get deployments
    kubectl get services
    kubectl get configmaps
    kubectl get secrets
    kubectl get namespaces
    

    Lists all resources of a given type in the current namespace.

  • List resources across all namespaces

    kubectl get pods --all-namespaces
    kubectl get deployments --all-namespaces
    

    Lists all resources of a given type across all namespaces.

  • Get resources in a specific namespace

    kubectl get pods -n kube-system
    

    Lists all pods in the kube-system namespace.

  • Describe a resource

    kubectl describe pod my-app-pod-abcde
    kubectl describe deployment my-app-deployment
    

    Shows detailed information about a specific resource, including its status, events, and associated objects.

  • Get resource YAML/JSON

    kubectl get pod my-app-pod-abcde -o yaml
    kubectl get deployment my-app-deployment -o json
    

    Outputs the resource definition in YAML or JSON format.

  • Create a resource from a file

    kubectl apply -f deployment.yaml
    kubectl apply -f service.yaml
    

    Applies a configuration from a YAML or JSON file. This is the preferred way to create and update resources.

  • Delete a resource

    kubectl delete pod my-app-pod-abcde
    kubectl delete deployment my-app-deployment
    kubectl delete -f deployment.yaml
    

    Deletes a specific resource or resources defined in a file.

  • Edit a resource

    kubectl edit deployment my-app-deployment
    

    Opens the resource definition in your default editor for in-place modification.

  • Scale a deployment

    kubectl scale deployment my-app-deployment --replicas=5
    

    Sets the number of desired replicas for a deployment.

Pod and Container Operations

  • View logs for a pod

    kubectl logs my-app-pod-abcde
    

    Fetches logs from the primary container in a pod.

  • View logs for a specific container in a pod

    kubectl logs my-app-pod-abcde -c container-name
    

    Fetches logs from a specific container within a pod.

  • Stream logs from a pod

    kubectl logs -f my-app-pod-abcde
    

    Tails the logs of a pod in real-time.

  • Execute a command in a pod

    kubectl exec -it my-app-pod-abcde -- /bin/bash
    

    Opens an interactive shell in a pod.

  • Execute a non-interactive command in a pod

    kubectl exec my-app-pod-abcde -- ls /app
    

    Runs a command within a pod and prints its output.

  • Port-forward to a pod

    kubectl port-forward pod/my-app-pod-abcde 8080:80
    

    Forwards local port 8080 to port 80 on the specified pod.

  • Port-forward to a service

    kubectl port-forward service/my-app-service 9090:80
    

    Forwards local port 9090 to the service’s port 80.

Resource Definitions

  • Generate a deployment YAML

    kubectl create deployment my-app --image=nginx:latest --dry-run=client -o yaml > nginx-deployment.yaml
    

    Creates a deployment resource definition without actually creating it in the cluster. Useful for generating templates.

  • Generate a service YAML

    kubectl expose deployment my-app --port=80 --target-port=80 --type=ClusterIP --dry-run=client -o yaml > my-app-service.yaml
    

    Creates a service resource definition for an existing deployment.

Troubleshooting

  • Get events in the cluster

    kubectl get events
    kubectl get events --all-namespaces
    

    Lists cluster events, which can be helpful for diagnosing issues.

  • Get resource events

    kubectl describe pod my-app-pod-abcde
    

    Events related to a specific resource are listed at the bottom of its describe output.

  • Check rollout status of a deployment

    kubectl rollout status deployment/my-app-deployment
    

    Monitors the progress of a deployment’s rollout.

  • View previous container logs

    kubectl logs my-app-pod-abcde --previous
    

    Retrieves logs from a previous instance of a container that has been restarted.

Context Management

  • List available contexts

    kubectl config get-contexts
    

    Shows all configured Kubernetes contexts.

  • View current context

    kubectl config current-context
    

    Displays the currently active context.

  • Switch context

    kubectl config use-context cluster-context-name
    

    Changes the active context to a different cluster or user.

  • Set context for a single command

    kubectl --context=cluster-context-name get pods
    

    Overrides the current context for a single command.

Resource Types

kubectl get and kubectl describe support a wide range of resource types. Common ones include:

  • pods (or po)
  • deployments (or deploy)
  • services (or svc)
  • replicationcontrollers (or rc)
  • replicasets (or rs)
  • statefulsets (or sts)
  • daemonsets (or ds)
  • jobs
  • cronjobs
  • configmaps (or cm)
  • secrets
  • namespaces (or ns)
  • ingresses (or ing)
  • persistentvolumes (or pv)
  • persistentvolumeclaims (or pvc)
  • storageclasses (or sc)

You can see a full list with kubectl api-resources.

Common Patterns

  • Applying multiple files in a directory

    kubectl apply -f ./kubernetes-configs/
    

    Applies all .yaml and .json files in the specified directory.

  • Finding pods with a specific label

    kubectl get pods -l app=my-app
    

    Lists pods that have the label app set to my-app.

  • Finding pods and filtering by status

    kubectl get pods | grep Running
    

    Lists all pods and filters for those in a Running state.

  • Deleting pods matching a label selector

    kubectl delete pods -l app=my-app
    

    Deletes all pods with the label app=my-app.

  • Restarting a deployment (by deleting pods)

    kubectl delete pods -l app=my-app-deployment
    

    This forces the deployment controller to recreate the pods, effectively restarting the application.

  • Getting a shell into a running pod

    kubectl exec -it deployment/my-app-deployment -- /bin/bash
    

    Executes a shell in the first pod managed by my-app-deployment.

  • Viewing all resources in a namespace in a table

    kubectl get all -n default
    

    Shows a summary of common resources in the default namespace.

  • Getting the external IP of a LoadBalancer service

    kubectl get service my-loadbalancer-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
    

    Extracts the external IP address assigned to a service of type LoadBalancer.

  • Watching resource changes

    kubectl get pods -w
    kubectl get pods --watch
    

    Continuously watches for changes to pods.

  • Getting output in a custom column format

    kubectl get pods -o=custom-columns='NAME:.metadata.name,STATUS:.status.phase'
    

    Displays specific fields from pod objects in a custom table format.

  • Finding pods that are not Ready

    kubectl get pods --field-selector=status.phase!=Running,status.phase!=Succeeded
    

    Lists pods that are not in a Running or Succeeded phase.

Gotchas

  • kubectl apply vs kubectl create: apply is declarative and is designed for GitOps workflows. It tracks resource state and intelligently merges changes. create is imperative and will error if the resource already exists. Always prefer apply.
  • Default Namespace: If you don’t specify a namespace (-n), kubectl operates in the default namespace or the namespace set in your current context. This can lead to confusion if you expect resources to be in a different namespace.
  • Resource Deletion: kubectl delete can be destructive. When deleting a deployment, the associated pods are terminated. For stateful applications, ensure proper backup and shutdown procedures are in place.
  • kubectl exec and kubectl logs: These commands target specific pods. If a pod is restarted or replaced (e.g., during a deployment update), kubectl logs will show logs for the new pod, and kubectl exec will connect to the new pod. To see logs from a previous container instance, use kubectl logs --previous.
  • RBAC: If you encounter permission errors, it’s likely a Role-Based Access Control (RBAC) issue. Ensure your user or service account has the necessary permissions defined in Roles and RoleBindings.
  • Context Switching: Forgetting to switch contexts can lead to applying changes to the wrong cluster. Always verify your current context with kubectl config current-context.
  • Resource Naming: Resource names must be unique within a namespace. Avoid using the same name for different resource types if they reside in the same namespace.
  • Image Pull Errors: Pods might fail to start due to ImagePullBackOff or ErrImagePull. This usually indicates an issue with the image name, tag, or credentials for a private registry. Check kubectl describe pod for specific error messages.
  • kubectl port-forward Timeout: kubectl port-forward is a client-side command. If your kubectl client disconnects, the port-forwarding will stop. It’s not suitable for long-lived production access.