Configuration and Context Management
Show Specifed Kubeconfig Settings
Bash
kubectl config view
Use Multiple Kubeconfig Files
Bash
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view
Get User Password
Bash
kubectl config view -o jsonpath='{.users[?(@.name == "user")].user.password}'
Display Contexts and Switch
Bash
kubectl config get-contexts
kubectl config current-context
kubectl config use-context {my-cluster-name}
Set Cluster Entry and Proxy URL
Bash
kubectl config set-cluster my-cluster-name
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url
Add a New User and Set Namespace
Bash
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
kubectl config set-context --current --namespace=testnamespace
Context and Namespace Short Aliases
Bash
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'
Applying and Managing Resources
Apply Manifests
Bash
kubectl apply -f ./my-manifest.yaml # create resource(s)
kubectl apply -f ./my1.yaml -f ./my2.yaml # create from multiple files
kubectl apply -f ./dir # create resource(s) in all manifest files in dir
kubectl apply -f https://git.io/vPieo # create resource(s) from url
kubectl create deployment nginx --image=nginx # start a single instance of nginx
Create Job and CronJob
Bash
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"
Explain and Create Multiple YAML Objects
Bash
kubectl explain pods
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep
# ... (continues)
EOF
Create Secret with Several Keys
Bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo -n "p@sswd" | base64 -w0)
username: $(echo -n "jhon" | base64 -w0)
EOF
View and Find Resources
Bash
kubectl get services # List all services in the namespace
kubectl get pods --all-namespaces # List all pods in all namespaces
kubectl get pods -o wide # List all pods in the current namespace, with more details
kubectl get deployment my-dep # List a particular deployment
kubectl get pods # List all pods in the namespace
kubectl get pod my-pod -o yaml # Get a pod's YAML
Update Resources and Rollback
Bash
kubectl set image deployment/frontend www=image:v2 # Rolling update "www" containers of "frontend" deployment, updating the image
kubectl rollout history deployment/frontend # Check the history of deployments including the revision
kubectl rollout undo deployment/frontend # Rollback to the previous deployment
kubectl rollout undo deployment/frontend --to-revision=2 # Rollback to a specific revision
kubectl rollout status -w deployment/frontend # Watch rolling update status of "frontend" deployment until completion
kubectl rollout restart deployment/frontend # Rolling restart of the "frontend" deployment
Patching Resources and Editing
Bash
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # Partially update a node
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' # Update a container's image; spec.containers[*].name is required because it's a merge key
kubectl edit svc/docker-registry # Edit the service named docker-registry
KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor
Scaling Resources
Bash
kubectl scale --replicas=3 deployment/test # Scale a deployment named 'test' to 3
kubectl scale --replicas=3 -f test.yaml # Scale a resource specified in "test.yaml" to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # If the deployment named mysql's current size is 2, scale mysql to 3
kubectl scale --replicas=5 deployment/foo deployment/bar deployment/baz # Scale multiple replication controller
Deleting Resources
Bash
kubectl delete -f ./pod.json # Delete a pod using the type and name specified in pod.json
kubectl delete pod unwanted --now # Delete a pod with no grace period
kubectl delete pod,service baz foo # Delete pods and services with same names "baz" and "foo"
kubectl delete pods,services -l name=myLabel # Delete pods and services with label name=myLabel
kubectl -n my-ns delete pod,svc --all # Delete all pods and services in namespace my-ns,
# Delete all pods matching the awk pattern1 or pattern2
kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod
Interacting with Running Pods
Logs and Exec Commands
Bash
# Dump pod logs (stdout)
kubectl logs my-pod
# Dump pod logs, with label name=myLabel (stdout)
kubectl logs -l name=myLabel
# Dump pod logs (stdout) for a previous instantiation of a container
kubectl logs my-pod --previous
# Dump pod container logs (stdout, multi-container case)
kubectl logs my-pod -c my-container
# Dump pod container logs, with label name=myLabel (stdout)
kubectl logs -l name=myLabel -c my-container
# Dump pod container logs (stdout, multi-container case) for a previous instantiation of a container
kubectl logs my-pod -c my-container --previous
# Stream pod logs (stdout)
kubectl logs -f my-pod
# Stream pod container logs (stdout, multi-container case)
kubectl logs -f my-pod -c my-container
# Stream all pods logs with label name=myLabel (stdout)
kubectl logs -f -l name=myLabel --all-containers
# Run pod as interactive shell
kubectl run -i --tty busybox --image=busybox:1.28 -- sh
# Start a single instance of nginx pod in the namespace of mynamespace
kubectl run nginx --image=nginx -n mynamespace
# Generate spec for running pod nginx and write it into a file called pod.yaml
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
# Attach to Running Container
kubectl attach my-pod -i
# Listen on port 5000 on the local machine and forward to port 6000 on my-pod
kubectl port-forward my-pod 5000:6000
# Run command in existing pod (1 container case)
kubectl exec my-pod -- ls /
# Interactive shell access to a running pod (1 container case)
kubectl exec --stdin --tty my-pod -- /bin/sh
# Run command in existing pod (multi-container case)
kubectl exec my-pod -c my-container -- ls /
# Show metrics for a given pod and its containers
kubectl top pod POD_NAME --containers
# Show metrics for a given pod and sort it by 'cpu' or 'memory'
kubectl top pod POD_NAME --sort-by=cpu
Copying Files to and from Containers
Bash
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar # Copy /tmp/foo from a remote pod to /tmp/bar locally
Interacting with Deployments and Services
Bash
kubectl logs deploy/my-deployment # dump Pod logs for a Deployment (single-container case)
kubectl logs deploy/my-deployment -c my-container # dump Pod logs for a Deployment (multi-container case)
kubectl port-forward svc/my-service 5000 # listen on local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000:my-service-port # listen on local port 5000 and forward to Service target port with name <my-service-port>
kubectl port-forward deploy/my-deployment 5000:6000 # listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment>
kubectl exec deploy/my-deployment -- ls # run command in first Pod and first container in Deployment (single- or multi-container cases)
Interacting with Nodes and Cluster
Bash
kubectl cordon my-node # Mark my-node as unschedulable
kubectl drain my-node # Drain my-node in preparation for maintenance
kubectl uncordon my-node # Mark my-node as schedulable
kubectl top node my-node # Show metrics for a given node
kubectl cluster-info # Display addresses of the master and services
kubectl cluster-info dump # Dump current cluster state to stdout
kubectl cluster-info dump --output-directory=/path/to/cluster-state # Dump current cluster state to /path/to/cluster-state
# View existing taints on which exist on current nodes.
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'
Taints and Resource Types
Bash
# View existing taints on current nodes
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value'
# Add a new taint to a node
kubectl taint nodes node-1 key=value:NoSchedule
# Remove a taint from a node
kubectl taint nodes node-1 key:NoSchedule-
# List all supported resource types with details
kubectl api-resources
# List all namespaced resources
kubectl api-resources --namespaced=true
# List all non-namespaced resources
kubectl api-resources --namespaced=false
# List resources with simple output (only resource names)
kubectl api-resources -o name
# List resources with expanded (wide) output
kubectl api-resources -o wide
# List resources that support "list" and "get" verbs
kubectl api-resources --verbs=list,get
# List resources in the "extensions" API group
kubectl api-resources --api-group=extensions
Advanced Operations
Get Custom Resource Definitions (CRDs)
Bash
kubectl get crd
Display Raw Resource Confi
Bash
kubectl get pod my-pod -o=json
Export Resources to YAML
Bash
kubectl get pod my-pod -o=yaml > pod.yaml
Diff Resources Before and After Applying
Bash
kubectl diff -f ./my-manifest.yaml
View Applied Configuration
Bash
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}'
Generate Manifests for Existing Resources
Bash
kubectl get pod my-pod -o=json > my-pod.json
Namespace Operations
List Pods in a Namespace
Bash
kubectl get pods --namespace=my-namespace
Set the Default Namespace for a Context
Bash
kubectl config set-context --current --namespace=my-namespace
Use a Different Namespace for a Single Command
Bash
kubectl get pods --namespace=other-namespace
Troubleshooting and Debugging
Get Events for a Resource
Bash
kubectl describe pod my-pod
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl events --types=Warning
Check Pod’s ContainerIDs
Bash
kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3
Output Decoded Secrets
Bash
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'
List Secrets Used by Pods
Bash
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
Check Nodes’ Readiness
Bash
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
&& kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
List All Pods in Running Phase
Bash
kubectl get pods --field-selector=status.phase=Running
Output Formatting
Output in JSON Format
Bash
kubectl get pods -o=json
kubectl describe pod my-pod -o=json
Custom Output Using JSONPath
Bash
kubectl get nodes -o json | jq -c 'paths|join(".")'
kubectl get pods -o json | jq -c 'paths|join(".")'
Output in YAML Format
Bash
kubectl get pods -o=yaml
kubectl describe pod my-pod -o=yaml
Custom Output Columns
Bash
kubectl get pods -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase
kubectl get nodes -o=custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'
Debugging and Verbosity
Display API Requests
Bash
kubectl get pods --v=8
kubectl describe pod my-pod --v=9
Display HTTP Request Headers
Bash
kubectl get pods --v=7
Display HTTP Request Contents
Bash
kubectl get pods --v=8
Table Of Commands
Command | Description |
---|---|
kubectl config view | Show specified Kubeconfig settings |
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view | Use multiple Kubeconfig files |
kubectl config view -o jsonpath='{.users[?(@.name == "user")].user.password}' | Get user password |
kubectl config get-contexts | Display contexts |
kubectl config current-context | Display the current context |
kubectl config use-context {my-cluster-name} | Switch to a specific context |
kubectl config set-cluster my-cluster-name | Set cluster entry |
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url | Set cluster entry and proxy URL |
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword | Add a new user and set namespace |
kubectl config set-context --current --namespace=testnamespace | Set the namespace for the current context |
`alias kx=’f() { [ “$1” ] && kubectl config use-context $1 | |
`alias kn=’f() { [ “$1” ] && kubectl config set-context –current –namespace $1 | |
kubectl apply -f ./my-manifest.yaml | Apply manifests to create resource(s) |
kubectl apply -f ./my1.yaml -f ./my2.yaml | Apply from multiple files |
kubectl apply -f ./dir | Apply resource(s) in all manifest files in a directory |
kubectl apply -f https://git.io/vPieo | Apply resource(s) from URL |
kubectl create deployment nginx --image=nginx | Create a deployment with a specified image |
kubectl create job hello --image=busybox:1.28 -- echo "Hello World" | Create a job |
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World" | Create a cron job |
kubectl explain pods | Explain and create multiple YAML objects |
kubectl apply -f - <<EOF...EOF | Create multiple YAML objects from stdin |
kubectl apply -f - <<EOF...EOF | Create a secret with several keys |
kubectl get services | View services in the namespace |
kubectl get pods --all-namespaces | List pods in all namespaces |
kubectl get pods -o wide | List pods in the current namespace with more details |
kubectl get deployment my-dep | List a particular deployment |
kubectl get pods | List all pods in the namespace |
kubectl get pod my-pod -o yaml | Get a pod’s YAML |
kubectl set image deployment/frontend www=image:v2 | Update resources – rolling update |
kubectl rollout history deployment/frontend | Check deployment history |
kubectl rollout undo deployment/frontend | Rollback to the previous deployment |
kubectl rollout undo deployment/frontend --to-revision=2 | Rollback to a specific revision |
kubectl rollout status -w deployment/frontend | Watch rolling update status |
kubectl rollout restart deployment/frontend | Rolling restart of the deployment |
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' | Patch node to mark as unschedulable |
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' | Patch pod container’s image |
kubectl edit svc/docker-registry | Edit the service named docker-registry |
KUBE_EDITOR="nano" kubectl edit svc/docker-registry | Use an alternative editor |
kubectl scale --replicas=3 deployment/test | Scale a deployment to 3 replicas |
kubectl scale --replicas=3 -f test.yaml | Scale a resource specified in “test.yaml” to 3 |
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql | Scale deployment if current size is 2 |
kubectl scale --replicas=5 deployment/foo deployment/bar deployment/baz | Scale multiple replication controllers |
kubectl delete -f ./pod.json | Delete a pod using the type and name specified in pod.json |
kubectl delete pod unwanted --now | Delete a pod with no grace period |
kubectl delete pod,service baz foo | Delete pods and services with specified names |
kubectl delete pods,services -l name=myLabel | Delete pods and services with label name=myLabel |
kubectl -n my-ns delete pod,svc --all | Delete all pods and services in namespace my-ns |
`kubectl get pods -n mynamespace –no-headers=true | awk ‘/pattern1 |
kubectl logs my-pod | Dump pod logs (stdout) |
kubectl logs -l name=myLabel | Dump pod logs with label name=myLabel (stdout) |
kubectl logs my-pod --previous | Dump pod logs for a previous instantiation of a container |
kubectl logs my-pod -c my-container | Dump pod container logs (stdout, multi-container case) |
kubectl logs -l name=myLabel -c my-container | Dump pod container logs with label name=myLabel (stdout) |
kubectl logs my-pod -c my-container --previous | Dump pod container logs for a previous instantiation of a container |
kubectl logs -f my-pod | Stream pod logs (stdout) |
kubectl logs -f my-pod -c my-container | Stream pod container logs (stdout, multi-container case) |
kubectl logs -f -l name=myLabel --all-containers | Stream all pods logs with label name=myLabel (stdout) |
kubectl run -i --tty busybox --image=busybox:1.28 -- sh | Run pod as interactive shell |
kubectl run nginx --image=nginx -n mynamespace | Start a single instance of nginx pod in the specified namespace |
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml | Generate spec for running pod nginx |
kubectl attach my-pod -i | Attach to running container |
kubectl port-forward my-pod 5000:6000 | Listen on port 5000 on the local machine and forward to port 6000 on my-pod |
kubectl exec my-pod -- ls / | Run command in existing pod (single-container case) |
kubectl exec --stdin --tty my-pod -- /bin/sh | Interactive shell access to a running pod (single-container case) |
kubectl exec my-pod -c my-container -- ls / | Run command in existing pod (multi-container case) |
kubectl top pod POD_NAME --containers | Show metrics for a given pod and its containers |
kubectl top pod POD_NAME --sort-by=cpu | Show metrics for a given pod and sort by ‘cpu’ |
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir | Copy local directory to a remote pod in the current namespace |
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container | Copy local file to a remote pod in a specific container |
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar | Copy local file to a remote pod in a specified namespace |
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar | Copy from a remote pod to a local directory |
kubectl logs deploy/my-deployment | Dump Pod logs for a Deployment (single-container case) |
kubectl logs deploy/my-deployment -c my-container | Dump Pod logs for a Deployment (multi-container case) |
kubectl port-forward svc/my-service 5000 | Listen on local port 5000 and forward to port 5000 on Service backend |
kubectl port-forward svc/my-service 5000:my-service-port | Listen on local port 5000 and forward to Service target port |
kubectl port-forward deploy/my-deployment 5000:6000 | Listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment> |
kubectl exec deploy/my-deployment -- ls | Run command in the first Pod and first container in Deployment |
kubectl get crd | Get Custom Resource Definitions (CRDs) |
kubectl get pod my-pod -o=json | Display raw resource configuration |
kubectl get pod my-pod -o=yaml > pod.yaml | Export resources to YAML |
kubectl diff -f ./my-manifest.yaml | Diff resources before and after applying |
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}' | View applied configuration |
kubectl get pod my-pod -o=json > my-pod.json | Generate manifests for existing resources |
kubectl get pods --namespace=my-namespace | List pods in a specific namespace |
kubectl config set-context --current --namespace=my-namespace | Set the default namespace for a context |
kubectl get events --sort-by=.metadata.creationTimestamp | Get events for a resource |
`kubectl get pods –all-namespaces -o jsonpath='{range .items[].status.initContainerStatuses[]}{.containerID}{“\n”}{end}’ | cut -d/ -f3` |
`kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{“### “}}{{$k}}{{“\n”}}{{$v | base64decode}}{{“\n\n”}}{{end}}’` |
`kubectl get pods -o json | jq ‘.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name’ |
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect' | View existing taints on nodes |
kubectl taint nodes node-1 key=value:NoSchedule | Add a new taint to a node |
kubectl taint nodes node-1 key:NoSchedule- | Remove a taint from a node |
kubectl api-resources | List all supported resource types with details |
kubectl api-resources --namespaced=true | List all namespaced resources |
kubectl api-resources --namespaced=false | List all non-namespaced resources |
kubectl api-resources -o name | List resources with simple output (only resource names) |
kubectl api-resources -o wide | List resources with expanded (wide) output |
kubectl api-resources --verbs=list,get | List resources that support “list” and “get” verbs |
kubectl api-resources --api-group=extensions | List resources in the “extensions” API group |
kubectl get pods -o=json | Get custom resource definitions (CRDs) |
kubectl get pod my-pod -o=json | Display raw resource configuration |
kubectl get pod my-pod -o=yaml > pod.yaml | Export resources to YAML |
kubectl diff -f ./my-manifest.yaml | Diff resources before and after applying |
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}' | View applied configuration |
kubectl get pod my-pod -o=json > my-pod.json | Generate manifests for existing resources |
kubectl get pods --namespace=my-namespace | List pods in a specific namespace |
kubectl config set-context --current --namespace=my-namespace | Set the default namespace for a context |
kubectl get events --sort-by=.metadata.creationTimestamp | Get events for a resource |
kubectl describe pod my-pod | Describe pod details |
kubectl get pods --v=8 | Display API requests |
kubectl describe pod my-pod --v=9 | Display API requests with high verbosity |
kubectl get pods --v=7 | Display HTTP request headers |
kubectl get pods --v=8 | Display HTTP request contents |