Kubernetes Commands
Basic commands
$ kubectl cluster-infoto get cluster information and$ kubectl get nodesto get the nodes available in the cluster.
Pod
$ kubectl run myapp --image=thomaspk/webcreate a pod from the docker hub image thomaspk/web. It actually creates a deployment internally.$ kubectl run myapp --image=nginx --dry-run=client -o yaml > nginx.yamlto create a basic pod definition yaml file. Note that the previous$ kubectl run --generator=run-pod/v1has been deprecated and removed from Kubernetes version 1.18 onwards.$ kubectl run debian01 --rm -it --image=debian -- /bin/shto create a Debian pod with hostname debian01 and runs the shell interactively, which is especially useful for testing and debugging networking issues. Then issue a command like$ wget --spider http://192.168.1.70Useful to check if a remote web service or web site is accessible from the pod.$ kubectl run --generator=run-pod/v1 messaging --image=redis:alpine -l tier=msgto create a pod named messaging from the redis:alpine image, having the labeltier: msg. Useful$ kubectl run --generator=run-pod/v1 my-busybox --image=buxybox --command sleep 3600--dry-run -o yaml > busybox.yamlto create busybox image which runs the commandsleep 3600.$ kubectl apply -f poc-pod.yamlcreate a pod according to the yaml file configuration
Cronjob
$ kubectl create cronjob test-job --image=busybox --schedule="*/1 * * * *"to create a Kubernetes cronjob with a schedule.$ kubectl create cronjob --helpto view other options for this imperative command.
Deployments
$ kubectl create deployment myapp --image=nginxto create an nginx deployment called myapp without creating a yaml file. This is the quickest way, especially for exams. Useful$ kubectl create deployment myapp --image=nginx --dry-run -o yaml > myapp-deployment.yamlto create a deployment file without creating a deployment.
Services
$ kubectl expose pod myapp --type=LoadBalancer --name myapp-httpto expose the pod externally. Important there is no = after--name. Note that only cloud based Kubernetes Clusters have a LoadBalancer integrated. Custom Kubernetes Clusters do not support LoadBalancer and instead only NodePort and Ingress Controllers. For details, see https://stackoverflow.com/questions/44110876/kubernetes-service-external-ip-pending$ kubectl create service loadbalancer nc-svc --tcp=80 --dry-run=client -o yaml > nc-svc.yamlto create a service file without creating the service. The service namenc-svcand port specifiers are mandatory. The service types supported areclusterip,loadbalancer,nodeportorexternalnameare mandatory.
get
$ kubectl get nodesto show a list of nodes running in the cluster.$ kubectl get podsshows the list of running pods.$ kubectl get po --show-labelswill display pod information as well its labels.$ kubectl get po -L env,purposedisplays only theenvandpurposelabels for the listed pods.$ kubectl get deploylist the deployments$ kubectl get pods --all-namespacesto get all pods in all namespaces, i.e., all pods running on the cluster.$ watch kubectl get po,svc,deploy -o wideto watch the output every 2 seconds.$ watch kubectl get all -o widewatches pods, services, deployments and replicasets.$ kubectl get jobsto list the jobs to see if they have completed.$ kubectl get networkpolicyto list network policies. Seldom Used Easy to Forget
config
$ kubectl config current-contextget the configuration for the current context.$ kubectl config set-context --current --namespace=DVL1987to move the current context namespace toDVL1987$ kubectl config set-context $(kubectl config current-context) --namespace=devto permanently move kubectl to work in the dev namespace. Note This was the old way of changing context.$ kubectl --kubeconfig ~/.kube/sg-pats-adam-config get po,svcuses a different configuration file from the default in ~/.kube/config.
Common
$ kubectl describe pods webshows the details of the web pod$ kubectl delete pods/webdeletes the web pod.$ kubectl delete -f my-web-pod.yamldeletes the pod described in my-web-pod.yaml$ kubectl delete all --allselect all resource objects in the current namespace and delete all. Seldom Used Easy to Forget$ kubectl logs webdisplays the logs for the web pod.$ kubectl logs -f webkeeps reading the logs continuously. Note that logs are rotated daily and when it reaches 10MB in size. The-c <container name>can be used to specify the container in multi-container pods.$ kubectl port-forward <pod name> 1234:8080forwards port 8080 for the pod to the localhost at port 1234$ kubectl edit svc myappedits the myapp service. Change thespec.typefield value fromClusterIPtoNodeIPto expose the Node’s IP address.$ kubectl explain podwill list out the different field definitions that can be defined in the object ( in this case pod) yaml file.$ kubectl explain pod.specwill list out the field definitions for the pod object.$ kubectl explain PersistentVolumeClaim.spec.resourceslist out all fields for theresourcedefinition.$ kubectl explain pod.metadata --recursivewill list all the options available under the Pod.metadata object.$ kubectl attach my-pod -ito attach to the main process running in the container and even sendstdinfrom your terminal to the process, such as Ctrl-C.Alternatively, you can also use
$ kubectl exec my-pod -- /bin/shto create and run /bin/sh in the pod interactively. The--tells the kubectl command line that all options have already specified and what is after--are the commands to be run in the pod.$ kubectl scale rs <replica_set_name> --replicas=6OR$ kubectl scale deploy <deployment_name> --replicas=5. Seldom Used Easy to Forget$ kubectl top nodeto get the resource statistics of node. You can also do$ kubectl top poto get the resource statistics of pods.
Labels
Labelling Pods
$ kubectl label po my-pod env=stagingto labelmy-podwith the environment label.$ kubectl label po my-pod env=production --overwriteto change theenvlabel’s value to production.$ kubectl get po -l env=stagingto see all pods in the staging environment. This is an example of the use of a label selector.$ kubectl delete po -l env=stagingto kill all pods with the label env==staging.
Labelling Nodes
$ kubectl label node tom-notes-deploy-f889b85c7-cjjvk gpu=trueto label the node. This is also the way to mark a node for affinity.$ kubectl get nodes -l gpu=trueto list pods with the labelgpu=true.$ kubectl get nodes --show-labelsto list nodes and their labels.
Namespaces
$ kubectl create ns devto create the dev namespace.$ kubectl get nsto get all name spaces in the cluster.$ kubectl get po --namespace=kube-systemto list all pods in thekube-systemnamespace.
Deployments
$ kubectl set image deploy <deployment_name> nginx=nginx:1.17to update the container image for the deployment imperatively.$ kubectl rollout restart deploy <deployment_name>to forcefully rollout a new deployment.$ kubectl rollout history deploy <deployment_name>to view the previous history of deployments.$ kubectl rollout undo deploy <deployment_name>to roll back to the previous version of the deployment. Or to go back to a specific revision of the deployment (e.g. revision 3), use$ kubectl rollout undo deployment <deployment_name> --to-revision=3.$ kubectl rollout status deploy <deployment_name>to check the status of a rollout process. Useful to find out if a canary release failed deployment, i.e. failed to be ready before minReadySeconds.$ kubectl rollout undo deploy <deployment_name>to undo an existing rollout.
Kubernetes Object mnemonic list
Reference URL https://blog.heptio.com/kubectl-resource-short-names-heptioprotip-c8eff9fb7202
cm: config maps
deploy: deployments
ds: daemon set
no: nodes
ns: namespace
po: pod
pv: persistent volume
rc: replication controller
rs: replication set
svc: service
ConfigMaps
$ kubectl create configmap fortune-config --from-literal=sleep-interval=25. Using the command line, this will create thefortune-configConfigMap which contains the keysleep-intervalwith a value of25.$ kubectl create configmap my-config --from-file=/path/to/dircreates a ConfigMap named my-config with keys and values from the files in the directory.$ kubectl create configmap my-config --from-file=config-file.confstores the content of the file config-file.conf under the keyconfig-file.conf.$ kubectl delete config-map fortune-configto delete thefortune-configconfig map. You can use$ kubectl get cmto display all config maps in the system anddescribethem to list the key value pairs in the config map.
Secrets Easy to Forget
$ kubectl create secret generic fortune-https --from-file=./fortune-secrets/to create secrets from the files in the fortune-secrets folder.$ kubectl create secret generic <secret-name> --from-literal=<key>=<value>to create secret key value pairs from the command line.$ echo -n 'password' | base64will convert the textpasswordto base64 format that can be put into a secrets declaration yaml file. Use$ echo -n cGFzc3dvcmQ= | base64 --decodeto decode the value.
Service Accounts
$ kubectl create serviceaccount dashboard-sawill create a new service account in the cluster called dashboard-sa. This account can be used to access Kubernetes functions.$ kubectl get serviceaccountwill display the list of service accounts in the cluster.$ kubectl describe serviceaccount dashboard-sawill display details of the newly created dahsboard-sa service account. It displays the following output.Name: dashboard-sa Namespace: default Labels: <none> Annotations: <none> Image pull secrets: <none> Mountable secrets: dashboard-sa-token-kbbdm Tokens: dashboard-sa-token-kbbdm Events: <none>
$ kubectl describe secret dashboard-sa-token-kbbdmwill display the details of this token used to authenticate and access the api-server.
Taints & Tollerations
$ kubectl taint nodes <node-name> key=value:NoScheduleto mark a node as tainted with theNoScheduleeffect. The other effects available arePreferNoScheduleandNoExecute.$ kubectl taint nodes <node-name> key=value:NoSchedule-to remove the taint from the node.To display the taint on a node, use
$ kubectl describe node <node_name> | lessand look for theTaints:section.