🍴 Fork and contribute. Your contribution is welcome 🙌
A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes. A comprehensive and example-rich guide suitable for learners of all levels. Get the book on Amazon.
Curated Kubernetes news, tutorials, tools, research papers, jobs, and more - delivered to your inbox every week. Subscribe and start receiving our free weekly newsletter.
If you're seeking a cozy sweatshirt to wear during your extended coding sessions or a mug to exhibit your passion for programming, you can find it all on ByteVibe
- Pods
- List all pods in namespace
<default> - View a pod in watch mode
- View all pods in watch mode
- List sorted pods
- List pods using a different output
- Formatting output
- List all pods in a namespace
- List all pods in all namespaces
- Create from an image
- Run pod in an interactive shell mode
- Run a command after creating a pod
- Executing a command in a running pod
- Create a pod: dry run mode (without really creating it)
- Patch a pod
- Create from a YAML file
- Export YAML from the dry run mode
- Create from STDIN
- Create multiple resources from STDIN
- Create in a namespace
- Create in a namespace from a file
- Delete pods
- Get pod logs
- List all container id of init container of all pods
- Show metrics for a given pod
- Show metrics for a given pod and all its containers
- List all pods in namespace
- Deployments
- Create a deployment
- Create a deployment with a predefined replica number
- Create a deployment with a predefined replica number and opening a port
- Create a deployment with a predefined replica number, opening a port and exposing it
- Get a deployment
- Watch a deployment
- List all deployments
- Update the image
- Scale a deployment
- Dry run and YAML output
- Create a deployment from a file
- Edit a deployment
- Rollback deployment
- Get rollout history
- Roll back to a previous revision
- Execute deployment rollout operations
- Port Forwarding
- Services
- Nodes
- Namespaces
- Service accounts
- Events
- Documentation
- Describing resources
- Editing resources
- Deleting Resources
- All get commands
- Abbreviations / Short forms of resource types
- Verbose Kubectl
- Cluster
- Kubectl context
- Show merged kubeconfig settings
- Use multiple kubeconfig
- Display the first user
- Get the password for the "admin" user
- Sets a user entry in kubeconfig
- Sets a user with a client key
- Sets a user with basic auth
- Sets a user with client certificate
- Set a context utilizing a specific config file
- Set a context utilizing a specific username and namespace.
- Alias
- Kubectl imperative (create) vs declarative (apply)
kubectl get pods
or
kubectl get pod
or
kubectl get po
kubectl get pod <pod> --watch
kubectl get pods -A --watch
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl get pods -o <json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>
Examples:
- JSON output
kubectl get pods -o json
or
kubectl get pods -ojson
or
kubectl get pods -o=json
- Wide output:
kubectl get pods -o wide
- Custom columns:
kubectl get pods -o custom-columns='DATA:spec.containers[*].image'
or
kubectl get pods -o custom-columns='DATA:spec.containers[*].volumeMounts'
or
kubectl get pods -o custom-columns='DATA:metadata.*'
To output details to your terminal window in a specific format, add the -o (or --output) flag to a supported kubectl command (source: K8s docs)
| Output format | Description |
|---|---|
-o=custom-columns=<spec> |
Print a table using a comma separated list of custom columns |
-o=custom-columns-file=<filename> |
Print a table using the custom columns template in the <filename> file |
-o=json |
Output a JSON formatted API object |
-o=jsonpath=<template> |
Print the fields defined in a jsonpath expression |
-o=jsonpath-file=<filename> |
Print the fields defined by the jsonpath expression in the <filename> file |
-o=name |
Print only the resource name and nothing else |
-o=wide |
Output in the plain-text format with any additional information, and for pods, the node name is included |
-o=yaml |
Output a YAML formatted API object |
kubectl get pods -n <namespace>
or
kubectl -n <namespace> get pods
or
kubectl --namespace <namespace> get pods
kubectl get pods --all-namespaces
or
kubectl get pods -A
kubectl run <pod> --generator=run-pod/v1 --image=<image>
In the following cheatsheet, we will be using images such as nginx or busybox.
Example:
kubectl run nginx --generator=run-pod/v1 --image=nginx
kubectl run busybox --generator=run-pod/v1 --image=busybox
kubectl run -i --tty nginx --image=nginx -- sh
kubectl run busybox --image=busybox -- sleep 100000
kubectl exec <pod> -- <command>
Or pass stdin to the container in TTY mode:
kubectl exec -it <pod> -- <command>
Example:
kubectl exec -it nginx -- ls -lrth /app/
kubectl run <pod> --generator=run-pod/v1 --image=nginx --dry-run
kubectl patch pod <pod> -p '<patch>'
Example:
kubectl patch pod <pod> -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
Another example:
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
kubectl create -f pod.yaml
kubectl run nginx --generator=run-pod/v1 --image=nginx --dry-run -o yaml
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx:latest
EOF
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: v1
kind: Pod
metadata:
name: busybox
spec:
containers:
- name: busybox
image: busybox
args:
- sleep
- "100"
kubectl run nginx --generator=run-pod/v1 --image=nginx -n <namespace>
kubectl create -f pod.yaml -n <namespace>
kubectl delete pod/<pod>
or
kubectl delete pod <pod>
If you create the pod from a file, you can also use:
kubectl delete -f pod.yaml
To force deletion:
kubectl delete pod <pod> --grace-period=0 --force
kubectl logs <pod>
or
Sometimes a pod contains more than 1 container. You need to filter the output to get logs for a specific container(s)
kubectl logs <pod> -c <container>
To follow the logs output (tail -f):
kubectl logs -f <pod>
If you need to output the logs for all pods with a label
kubectl logs -l <label_name>=<label_value>
Example:
kubectl logs -l env=prod
You can also view logs in a multi container case with labels:
kubectl logs -l <label_name>=<label_value> -c <container>
Or view all cotainers logs with a given label:
kubectl logs -f -l <label_name>=<label_value> --all-containers
kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3
kubectl top pod <pod>
kubectl top pod <pod> --containers
kubectl run <deployment> --image=<image>
or
kubectl create deployment <deployment> --image=<image>
kubectl run <deployment> --image=<image> --replicas=<number>
kubectl run <deployment> --image=<image> --replicas=<replicas> --port=<port>
Example:
kubectl run nginx --image=nginx --replicas=2 --port=80
Note: The default generator for kubectl run is --generator=deployment/apps.v1.
Note: --generator=deployment/apps.v1 is deprecated and will be removed in future versions. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
kubectl run nginx --image=nginx --replicas=2 --port=80 --expose
kubectl get deploy <deployment>
kubectl get deployment <deployment> --watch
or
kubectl get deployment <deployment> -w
Or using a shorter version:
kubectl get deploy <deployment> -w
Or even the longer one:
kubectl get deployments.apps <deployment> --watch
Same as listing pods, you have multiple options from namespace to output formatters:
kubectl get deploy -n <namespace>
kubectl get deploy --all-namespaces
kubectl get deploy -A
kubectl get deploy -oyaml
kubectl get deploy -owide
Rolling update "nginx" containers of "nginx" deployment, updating the image:
kubectl set image deployment/nginx nginx=nginx:1.9.1
Rolling update "api" containers of "backend" deployment, updating the image:
kubectl set image deployment/backend api=image:v2
kubectl scale --replicas=5 deployment/<deployment>
Note: You can use a shorter version:
kubectl scale --replicas=5 deploy/<deployment>
kubectl run nginx --image=nginx --replicas=2 --port=80 --dry-run -o yaml
kubectl apply -f deployment.yaml
kubectl edit deployment/<deployment>
After editing your deployment, you had an error, a solution can be rolling back to the old deployment status:
kubectl rollout undo deployment <deployment>
You can check the rollout history:
kubectl rollout history deployment <deployment>
kubectl rollout history deployment <deployment>
Example:
kubectl rollout history deployment nginx
gives you:
REVISION CHANGE-CAUSE
2 kubectl set image deployment/nginx nginx=nginx:1.9.1 --record=true
3 <none>
Using the information from the rollout history, we can get back our deployment to a given revision:
kubectl rollout undo deployment <deployment> --to-revision=<revision>
Example:
kubectl rollout undo deployment nginx --to-revision=2
kubectl rollout status deployment <deployment>
kubectl rollout pause deployment <deployment>
kubectl rollout resume deployment <deployment>
kubectl port-forward deployment <deployment> <locahost-port>:<deployment-port>
kubectl port-forward pod <pod> <locahost-port>:<pod-port>
Example:
Forward to localhost 8090 from pod 6379:
kubectl port-forward redis 8090:6379
kubectl port-forward pod <pod> <port>
Example: Listen on ports 8000 and 9000 on localhost, forwarded from the same ports in the pod (8000 and 9000)
kubectl port-forward pod nginx 8000 9000
kubectl port-forward pod <pod> :<pod-port>
Example:
kubectl port-forward pod nginx :80
kubectl port-forward --address localhost,<IP.IP.IP.IP> pod <pod> <locahost-port>:<pod-port>
Example:
kubectl port-forward --address localhost,10.10.10.1 pod redis 8090:6379
kubectl port-forward --address 0.0.0.0 pod <pod> <hosts-port>:<pod-port>
kubectl create service <clusterip|externalname|loadbalancer|nodeport> <service> [flags] [options]>
Examples:
kubectl create service clusterip myclusterip --tcp=5678:8080
kubectl create service loadbalancer myloadbalancer --tcp=80
You can use svc instead of service.
kubectl delete service myclusterip
kubectl delete service myloadbalancer
kubectl delete svc myclusterip
kubectl delete svc myloadbalancer
or
kubectl delete service myclusterip myloadbalancer
kubectl describe service <service>
kubectl get nodes
kubectl get nodes <node>
kubectl top node <node>
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
kubectl describe nodes <node>
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
kubectl cordon <node>
kubectl drain <node>
kubectl uncordon <node>
kubectl get namespaces
or
kubectl get ns
kubectl get namespace <namespace>
kubectl describe namespace <namespace>
kubectl create namespace <namespace>
or
kubectl create -f namespace.yaml
or
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Namespace
metadata:
name: mynamespace
EOF
kubectl delete namespace <namespace>
or
kubectl delete -f namespace.yaml
kubectl get serviceaccounts
or
kubectl get sa
kubectl get serviceaccount <serviceaccount>
or
kubectl get serviceaccounts <serviceaccount>
or
kubectl get sa <serviceaccount>
or
kubectl get sa/<serviceaccount>
kubectl create serviceaccount <serviceaccount>
kubectl delete serviceaccount <serviceaccount>
or
kubectl delete -f myserviceaccount.yaml
kubectl describe serviceaccount <serviceaccount>
kubectl get events -A
kubectl get events --sort-by=<JSONPath>
Example: Sorted by timestamp
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events -o <json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>
Example:
kubectl get events -owide
kubectl explain pod
kubectl explain service
kubectl describe <resource> <reosurce_name>
Example:
kubectl describe pod busybox
or
kubectl describe nodes minikube
Other possible resources you can use with describe:
apiservices.apiregistration.k8s.io
certificatesigningrequests.certificates.k8s.io
clusterrolebindings.rbac.authorization.k8s.io
clusterroles.rbac.authorization.k8s.io
componentstatuses
configmaps
controllerrevisions.apps
cronjobs.batch
csidrivers.storage.k8s.io
csinodes.storage.k8s.io
customresourcedefinitions.apiextensions.k8s.io
daemonsets.apps
daemonsets.extensions
deployments.apps
deployments.extensions
endpoints
events
events.events.k8s.io
horizontalpodautoscalers.autoscaling
ingresses.extensions
ingresses.networking.k8s.io
jobs.batch
leases.coordination.k8s.io
limitranges
mutatingwebhookconfigurations.admissionregistration.k8s.io
namespaces
networkpolicies.extensions
networkpolicies.networking.k8s.io
nodes
persistentvolumeclaims
persistentvolumes
poddisruptionbudgets.policy
pods
podsecuritypolicies.extensions
podsecuritypolicies.policy
podtemplates
priorityclasses.scheduling.k8s.io
replicasets.apps
replicasets.extensions
replicationcontrollers
resourcequotas
rolebindings.rbac.authorization.k8s.io
roles.rbac.authorization.k8s.io
runtimeclasses.node.k8s.io
secrets
serviceaccounts
services
statefulsets.apps
storageclasses.storage.k8s.io
validatingwebhookconfigurations.admissionregistration.k8s.io
volumeattachments.storage.k8s.io
kubectl edit service <service>
KUBE_EDITOR="vim" edit service <service>
Note: Change service by any editable resource type like pods.
kubectl delete -f <file>
kubectl delete pod,service <name1> <name2>
kubectl delete pods,services -l <label-name>=<label-value>
kubectl -n <namespace> delete pods,services --all
kubectl delte <namespace>
kubectl get all
kubectl get pods
kubectl get replicasets
kubectl get services
kubectl get nodes
kubectl get namespaces
kubectl get configmaps
kubectl get endpoints
| Resource type | Abbreviations |
|---|---|
| componentstatuses | cs |
| configmaps | cm |
| daemonsets | ds |
| deployments | deploy |
| endpoints | ep |
| event | ev |
| horizontalpodautoscalers | hpa |
| ingresses | ing |
| limitranges | limits |
| namespaces | ns |
| nodes | no |
| persistentvolumeclaims | pvc |
| persistentvolumes | pv |
| pods | po |
| podsecuritypolicies | psp |
| replicasets | rs |
| replicationcontrollers | rc |
| resourcequotas | quota |
| serviceaccount | sa |
| services | svc |
kubectl run nginx --image=nginx --v=5
| Verbosity | Description |
|---|---|
--v=0 |
Generally useful for this to always be visible to a cluster operator. |
--v=1 |
A reasonable default log level if you don't want verbosity. |
--v=2 |
Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems. |
--v=3 |
Extended information about changes. |
--v=4 |
Debug level verbosity. |
--v=6 |
Display requested resources. |
--v=7 |
Display HTTP request headers. |
--v=8 |
Display HTTP request contents. |
--v=9 |
Display HTTP request contents without truncation of contents. |
(Table source: K8s docs)
kubectl cluster-info
kubectl cluster-info dump
kubectl cluster-info dump --output-directory=</file/path>
Compares the current cluster state against the state that the cluster would be in if the manifest was applied
kubectl diff -f ./my-manifest.yaml
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
kubectl config view
KUBECONFIG=~/.kube/config1:~/.kube/config2:~/.kube/config3
kubectl config view -o jsonpath='{.users[*].name}'
kubectl config view -o jsonpath='{.users[].name}'
kubectl config view -o jsonpath='{.users[?(@.name == "admin")].user.password}'
kubectl config current-context
kubectl config get-contexts
kubectl config use-context <cluster>
kubectl config set-credentials <username> [options]
kubectl config set-credentials <user> --client-key=~/.kube/admin.key
kubectl config set-credentials --username=<username> --password=<password>
kubectl config set-credentials <user> --client-certificate=<path/to/cert> --embed-certs=true
kubectl config --kubeconfig=<config/path> use-context <cluster>
kubectl config set-context gce --user=cluster-admin --namespace=foo \
&& kubectl config use-context gce
alias k=kubectl
Set-Alias -Name k -Value kubectl
You tell your cluster what you want to create, replace or delete, not how you want you it to look like.
kubectl create -f <filename|url>
kubectl delete deployment <deployment-name>
kubectl delete deployment <deployment-filename>
kubectl delete deployment <deployment-url>
You tell your cluster how you want it to look like.
The creation, deletion and modification of objects is done via a single command. The declarative approach is a statement of the desired end result.
kubectl apply -f <filename|url>
kubectl delete -f <deployment-filename>
kubectl apply -f <deployment-filename>
If the deployment is deleted in <deployment-filename>, it will also be deleted from the cluster.