Guide to Essential Kubernetes CLI (kubectl) Commands

Published Apr 18, 2024

This post covers the general commands for kubernetes. Also installation steps for MacOS.

Installing Kubectl Client on Mac

Run below command to install via Brew.

brew install kubectl

or

bres install kubernetes-cli

Test the installation with the version check below.

kubectl version --client

Most used kubectl commands

List all namespaces

kubectl get namespaces

Kubernetes Namespaces

All the kubectl commands accept --namespace or -n argument. Alternatively you can use --all-namespaces flag to get results from all the namespaces.

Example:
To get list of all the resources from the default namespace

kubectl get all

To get list of all the resources

kubectl get all -n <namespace>

To get list of all the resources from all the namespaces

kubectl get all --all-namespaces

Cluster and Configuration:

  • kubectl version: Check kubectl version
  • kubectl cluster-info: Get information about the cluster
  • kubectl config current-context: View current context
  • kubectl config get-contexts: List available contexts
  • kubectl config use-context <name>: Set the active context

Resource Management:

  • kubectl get <resource>: List resources (e.g. get pods, get deployments)
  • kubectl describe <resource>: Show details about a resource
  • kubectl create -f <file>: Create resources from a YAML or JSON file
  • kubectl apply -f <file>: Create or update resources from a YAML or JSON file
  • kubectl delete <resource> <name>: Delete a resource by name

Pod Management:

  • kubectl logs <pod>: View logs of a pod
  • kubectl exec -it <pod> <command>: Run a command in a pod's container
  • kubectl cp <source> <dest>: Copy files between local machine and pods

Namespace Management:

  • kubectl get namespaces: List namespaces
  • kubectl create namespace <name>: Create a namespace

Service Management:

  • kubectl get services: List services
  • kubectl describe service <name>: View details of a service

Rollouts and Scaling:

  • kubectl rollout history deployment/<deployment_name>: View deployment history
  • kubectl scale deployment/<deployment_name> --replicas=<number>: Scale a deployment

Advanced Commands:

  • kubectl cordon <node>: Mark a node unschedulable
  • kubectl drain <node>: Drain a node in preparation for maintenance
  • kubectl port-forward <pod> <port>:<local_port>: Forward a pod port to your local machine

Resources:

#kubernetes #k8s #kube #kubectl #devops #sysadmin #containerorchestration #troubleshooting #debugging #sysops #cloudnative

Tags: tech cheat-sheet