Skip to main content

Cheatsheet: Kubernetes Commands

Updated Apr 07, 2022 ·

Pods and Parameters

PodsDescription
kubectl completion --helpSearch for "enabling completion"
source <(kubectl completion bash)Enable completion for kubectl
kubectl api-resourcesList shortnames for resources
kubectl get podsGet information about running pods in the current namespace
kubectl describe pod <pod>Describe a specific pod
kubectl expose pod <pod> --port=444 --name=frontendExpose the port of a pod (creates a new service)
kubectl port-forward <pod> 8080Port forward the exposed pod port to your local machine
kubectl attach <podname> -iAttach to the pod
kubectl exec <pod> -- commandExecute a command on the pod
kubectl exec -it pod-name bashSSH into the pod
kubectl label pods <pod> mylabel=awesomeAdd a label to a pod
kubectl run -i --tty busybox --image=busybox --restart=Never -- shRun a shell in a pod (useful for debugging)
ParametersDescription
--all-namespacesDisplay resources in all namespaces
-l LABEL-NAMEFilter by a specific label name
-l LABEL-NAME1,LABEL-NAME2Filter by multiple label names
--sort-by=metadata.creationTimestampSort pods by age
--output=yamlDisplay output in YAML format
--o yamlDisplay output in YAML format (can also use JSON)
--wideDisplay additional information in the output
--show-labelsShow labels attached to the pods

kubectl create vs. kubectl apply

  • kubectl create is used for Imperative Management, where you directly specify what you want to create, replace, or delete in the cluster.

    Example:

    kubectl create deployment my-deployment --image=nginx
  • kubectl apply is used for Declarative Management, where it ensures that changes to live objects (like scaling) are preserved even if you apply further changes.

    Example:

    kubectl apply -f my-manifest.yaml

Key difference:

  • kubectl create will fail if the resource already exists.
  • kubectl apply will update the resource without error.

Deployments

DeploymentsDescription
kubectl get deploymentsGet information on current deployments
kubectl get rsGet information about the replica sets
kubectl rollout status deployment/helloworld-deploymentGet the deployment status
kubectl set image deployment/helloworld-deployment k8s-demo=k8s-demoUpdate deployment with the new version of the k8s-demo image
kubectl edit deployment/helloworld-deploymentEdit the deployment object
kubectl rollout status deployment/helloworld-deploymentCheck the status of the rollout
kubectl rollout history deployment/helloworld-deploymentView the rollout history
kubectl rollout undo deployment/helloworld-deploymentRoll back to the previous version
kubectl rollout undo deployment/helloworld-deployment --to-revision=nRoll back to a specific version