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 versionDisplays the client and server versions of
kubectl. -
Get cluster info
kubectl cluster-infoPrints the addresses of the Kubernetes control plane and CoreDNS.
-
List available nodes
kubectl get nodesShows all nodes in the cluster with their status.
-
Describe a node
kubectl describe node worker-node-1Provides 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 namespacesLists all resources of a given type in the current namespace.
-
List resources across all namespaces
kubectl get pods --all-namespaces kubectl get deployments --all-namespacesLists all resources of a given type across all namespaces.
-
Get resources in a specific namespace
kubectl get pods -n kube-systemLists all pods in the
kube-systemnamespace. -
Describe a resource
kubectl describe pod my-app-pod-abcde kubectl describe deployment my-app-deploymentShows 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 jsonOutputs the resource definition in YAML or JSON format.
-
Create a resource from a file
kubectl apply -f deployment.yaml kubectl apply -f service.yamlApplies 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.yamlDeletes a specific resource or resources defined in a file.
-
Edit a resource
kubectl edit deployment my-app-deploymentOpens the resource definition in your default editor for in-place modification.
-
Scale a deployment
kubectl scale deployment my-app-deployment --replicas=5Sets the number of desired replicas for a deployment.
Pod and Container Operations
-
View logs for a pod
kubectl logs my-app-pod-abcdeFetches 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-nameFetches logs from a specific container within a pod.
-
Stream logs from a pod
kubectl logs -f my-app-pod-abcdeTails the logs of a pod in real-time.
-
Execute a command in a pod
kubectl exec -it my-app-pod-abcde -- /bin/bashOpens an interactive shell in a pod.
-
Execute a non-interactive command in a pod
kubectl exec my-app-pod-abcde -- ls /appRuns a command within a pod and prints its output.
-
Port-forward to a pod
kubectl port-forward pod/my-app-pod-abcde 8080:80Forwards local port 8080 to port 80 on the specified pod.
-
Port-forward to a service
kubectl port-forward service/my-app-service 9090:80Forwards 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.yamlCreates 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.yamlCreates a service resource definition for an existing deployment.
Troubleshooting
-
Get events in the cluster
kubectl get events kubectl get events --all-namespacesLists cluster events, which can be helpful for diagnosing issues.
-
Get resource events
kubectl describe pod my-app-pod-abcdeEvents related to a specific resource are listed at the bottom of its
describeoutput. -
Check rollout status of a deployment
kubectl rollout status deployment/my-app-deploymentMonitors the progress of a deployment’s rollout.
-
View previous container logs
kubectl logs my-app-pod-abcde --previousRetrieves logs from a previous instance of a container that has been restarted.
Context Management
-
List available contexts
kubectl config get-contextsShows all configured Kubernetes contexts.
-
View current context
kubectl config current-contextDisplays the currently active context.
-
Switch context
kubectl config use-context cluster-context-nameChanges the active context to a different cluster or user.
-
Set context for a single command
kubectl --context=cluster-context-name get podsOverrides 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(orpo)deployments(ordeploy)services(orsvc)replicationcontrollers(orrc)replicasets(orrs)statefulsets(orsts)daemonsets(ords)jobscronjobsconfigmaps(orcm)secretsnamespaces(orns)ingresses(oring)persistentvolumes(orpv)persistentvolumeclaims(orpvc)storageclasses(orsc)
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
.yamland.jsonfiles in the specified directory. -
Finding pods with a specific label
kubectl get pods -l app=my-appLists pods that have the label
appset tomy-app. -
Finding pods and filtering by status
kubectl get pods | grep RunningLists all pods and filters for those in a
Runningstate. -
Deleting pods matching a label selector
kubectl delete pods -l app=my-appDeletes all pods with the label
app=my-app. -
Restarting a deployment (by deleting pods)
kubectl delete pods -l app=my-app-deploymentThis 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/bashExecutes a shell in the first pod managed by
my-app-deployment. -
Viewing all resources in a namespace in a table
kubectl get all -n defaultShows a summary of common resources in the
defaultnamespace. -
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 --watchContinuously 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!=SucceededLists pods that are not in a
RunningorSucceededphase.
Gotchas
kubectl applyvskubectl create:applyis declarative and is designed for GitOps workflows. It tracks resource state and intelligently merges changes.createis imperative and will error if the resource already exists. Always preferapply.- Default Namespace: If you don’t specify a namespace (
-n),kubectloperates in thedefaultnamespace 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 deletecan be destructive. When deleting a deployment, the associated pods are terminated. For stateful applications, ensure proper backup and shutdown procedures are in place. kubectl execandkubectl logs: These commands target specific pods. If a pod is restarted or replaced (e.g., during a deployment update),kubectl logswill show logs for the new pod, andkubectl execwill connect to the new pod. To see logs from a previous container instance, usekubectl 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
ImagePullBackOfforErrImagePull. This usually indicates an issue with the image name, tag, or credentials for a private registry. Checkkubectl describe podfor specific error messages. kubectl port-forwardTimeout:kubectl port-forwardis a client-side command. If yourkubectlclient disconnects, the port-forwarding will stop. It’s not suitable for long-lived production access.