Chris Straw
SHARE:

Cheat Sheet for Managing Pods with kubectl

If you’re diving into Kubernetes, mastering kubectl It is essential—especially when managing Pods, the smallest and simplest unit in the Kubernetes ecosystem. Whether you’re just starting or looking for a quick reference, this cheat sheet will streamline your workflow.


1. Basic Pod Operations

List Pods

# List all Pods in the current namespace:
kubectl get pods

# List all Pods across all namespaces:
kubectl get pods --all-namespaces

Inspect Pods

# Describe a specific Pod:
kubectl describe pod <pod-name>

# Get detailed Pod info in YAML format:
kubectl get pod <pod-name> -o yaml

# Get Pod IPs and Node info:
kubectl get pods -o wide

2. Creating and Deleting Pods

Create Pods

# Create a Pod from a YAML file:
kubectl apply -f <pod-definition.yaml>

# Run a simple Pod directly from the command line:
kubectl run <pod-name> --image=<image-name>

Delete Pods

# Delete a specific Pod:
kubectl delete pod <pod-name>

#Force delete a Pod (immediate termination):
kubectl delete pod <pod-name> --grace-period=0 --force

3. Interacting with Pods

Viewing Logs

# View logs from a Pod:
kubectl logs <pod-name>

# View logs from a specific container in a Pod:
kubectl logs <pod-name> -c <container-name>

# Stream live logs:
kubectl logs -f <pod-name>

Executing Commands Inside Pods

# Run a command inside a Pod:
kubectl exec -it <pod-name> -- <command>
# Example: kubectl exec -it my-pod -- /bin/bash

# Start a shell session inside a Pod:
kubectl exec -it <pod-name> -- /bin/sh

Copying Files

# Copy files from a Pod to your local machine:
kubectl cp <pod-name>:<path-inside-pod> <path-on-local-machine>

# Copy files from your local machine to a Pod:
kubectl cp <path-on-local-machine> <pod-name>:<path-inside-pod>

4. Troubleshooting Pods

Checking Pod Status

# Check Pod status with more details:
kubectl get pods -o wide

# List all Pods with detailed statuses:
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

Debugging Tools

# Attach to a running Pod for debugging:
kubectl attach -it <pod-name>

# Port forward from your local machine to a Pod:
kubectl port-forward pod/<pod-name> <local-port>:<pod-port>

5. Filtering & Sorting Pods

Using Labels and Selectors

# List Pods with a specific label:
kubectl get pods -l <label-key>=<label-value>

Sorting and Field Selectors

# Sort Pods by age (creation timestamp):
kubectl get pods --sort-by=.metadata.creationTimestamp

# Get only running Pods:
kubectl get pods --field-selector=status.phase=Running

6. Working with Namespaces

Managing Namespaces

# List Pods in a specific namespace:
kubectl get pods -n <namespace-name>

# Set a default namespace for all `kubectl` commands:
kubectl config set-context --current --namespace=<namespace-name>