List of Kubernetes commands for daily use cases.

Biswanath Giri
8 min readMay 7, 2023

--

Nodes

$ kubectl get no
$ kubectl get no -o wide
$ kubectl describe no
$ kubectl get no -o yaml
$ kubectl get node - selector =[label_name]
$ kubectl get nodes -o j sonpat h=' { . i t ems[ * ] . st at us. addresses [ ?( @. type==" External IP" ) ] . address} '
$ kubectl top node [ node_name]

Pods

$ kubectl get po
$ kubectl get po - owide
$ kubectl describe po
$ kubectl get po - - show- labels
$ kubectl get po - l app=ngi nx
$ kubectl get po -o yaml
$ kubectl get pod [pod_name] -o yaml - export
$ kubectl get pod [pod_name] -o yaml - export> nameof file.yaml
$ kubectl get pods - field- selector status. phase=Running

Namespaces

$ kubectl get ns
$ kubectl get ns -o yaml
$ kubectl describe ns

Deployments

$ kubectl get deploy
$ kubectl describe deploy
$ kubectl get deploy -o wide
$ kubectl get deploy -o yaml

Services

$ kubectl get svc
$ kubectl describe svc
$ kubectl get svc -o wide
$ kubectl get svc -o yaml
$ kubectl get svc - show-labels

DaemonSets

$ kubectl get ds
$ kubectl get ds - all -namespaces
$ kubectl describe ds [daemonset _name] -n [namespace_name]
$ kubectl get ds [ds_name] -n [ ns_name] -o yaml

Events

$ kubectl get events
$ kubectl get events -n kube-system
$ kubectl get events -w

Logs

$ kubectl logs [ pod_name]
$ kubectl logs - since=1h [pod_name]
$ kubectl logs - tail =20 [pod_name]
$ kubectl logs -f -c [container_name] [pod_name]
$ kubectl logs [pod_name]>pod.log

ServiceAccounts

$ kubectl get sa
$ kubectl get sa -o yaml
$ kubectl get serviceaccounts default -o yaml > . / sa. yaml
$ kubectl replace service account default - f . / sa.yaml

ReplicaSets

$ kubectl get rs
$ kubectl describe rs
$ kubectl get rs -o wide
$ kubectl get rs -o yaml

Roles

$ kubectl get roles - all-namespaces
$ kubectl get roles - all-namespaces -o yaml

Secrets

$ kubectl get secrets
$ kubectl get secrets - all-namespaces
$ kubectl get secrets -o yaml

ConfigMaps

$ kubectl get cm
$ kubectl get cm - all-namespaces
$ kubectl get cm - all-namespaces -o yaml

Ingress

$ kubectl get ing
$ kubectl get ing - all-namespaces

PersistentVolume

$ kubectl get pv
$ kubectl describe pv

PersistentVolumeClaim

$ kubectl get pvc
$ kubectl describe pvc

StorageClass

$ kubectl get sc
$ kubectl get sc -o yaml

MultipleResources

$ kubectl get svc, po
$ kubectl get deploy, no
$ kubectl get all
$ kubectl get all - all-namespaces

Taint

$ kubectl taint [node_name] [taint _name]

Labels

$ kubectl label [node_name] disktype=ssd
$ kubectl label [pod_name] env=prod

Cordon/Uncordon

$ kubectl cordon [node_name]
$ kubectl uncordon [node_name]

Drain

$ kubectl drain [ node_name]

Nodes/Pods

$ kubectl delete node [node_name]
$ kubectl delete pod [pod_name]
$ kubectl edit node [node_name]
$ kubectl edit pod [pod_name]

Deployments/Namespaces

$ kubectl edit deploy [deploy_name]
$ kubectl delete deploy [deploy_name]
$ kubectl expose deploy [deploy_name] - port=80 - type=NodePort
$ kubectl scale deploy [deploy_name] - replicas=5
$ kubectl delete ns
$ kubectl edit ns [ns_name]

DaemonSets

$ kubectl edit ds [ds_name] -n kube-system
$ kubectl delete ds [ds_name]

Services

$ kubectl edit svc [svc_name]
$ kubectl delete svc [svc_name]

ServiceAccounts

$ kubectl edit sa [sa_name]
$ kubectl delete sa [sa_name]

Annotate

$ kubectl annotate po [pod_name] [annotation]
$ kubectl annotate no [node_name]

CreatingaPod

$ kubectl create -f [name_of _f i l e]
$ kubectl apply -f [name_of _f i l e]
$ kubectl run [pod_name] - image=nginx - restart=Never
$ kubectl run [pod_name] - generator=run-pod/ v1 - image=nginx
$ kubectl run [pod_name] - image=nginx - restart=Never

CreatingaService

$ kubectl create svc nodeport [svc_name] - tcp=8080:80

CreatingaDeployment

$ kubectl create -f [name_of_file]
$ kubectl apply -f [name_of_file]
$ kubectl create deploy [deploy_name] - image=nginx

Requests APICall

$ kubectl get - raw /apis/metrics.k8s.i o/

Cluster Info

$ kubectl config
$ kubectl cluster -info
$ kubectl get component statuses

InteractivePod

$ kubectl run [pod_name] - image=busybox - rm -it - restart =Never - sh

Output YAMLto aFile

$ kubectl create deploy [deploy_name] - image=ngi nx - dry-run -o yaml > depl oy. yaml
$ kubectl get po [pod_name] -o yaml - export >pod.yaml

GettingHelp

$ kubectl -h
$ kubectl create -h
$ kubectl run -h
$ kubectl explain deploy.spec

Run curl test temporarily

kubectl run - generator=run-pod/v1 - rm mytest - image=yauritux/busybox-cu

Run wget test temporarily

kubectl run - generator=run-pod/v1 - rm mytest - image=busybox -it wget

Run nginx deployment with 2 replicas

kubectl run my-nginx - image=nginx - replicas=2 - port=80

Run nginx pod and expose it

kubectl run my-nginx - restart=Never - image=nginx - port=80 - expose

Run nginx deployment and expose it

kubectl run my-nginx - image=nginx - port=80 - expose

List authenticated contexts

kubectl config get-contexts, ~/.kube/config

Set namespace preference

kubectl config set-context <context_name> - namespace=<ns_name>

List pods with nodes info

kubectl get pod -o wide

List everything

kubectl get all - all-namespaces

Get all services

kubectl get service - all-namespaces

Get all deployments

kubectl get deployments - all-namespaces

Show nodes with labels

kubectl get nodes - show-labels

Get resources with json output

kubectl get pods - all-namespaces -o json

Validate yaml file with dry run

kubectl create - dry-run - validate -f pod-dummy.yaml

Start a temporary pod for testing

kubectl run - rm -i -t - image=alpine test-$RANDOM - sh

kubectl run shell command

kubectl exec -it mytest - ls -l /etc/hosts

Get system conf via configmap

kubectl -n kube-system get cm kubeadm-config -o yaml

Get deployment yaml

kubectl -n denny-websites get deployment mysql -o yaml

Explain resource

kubectl explain pods, kubectl explain svc

Watch pods

kubectl get pods -n wordpress - watch Query healthcheck

Endpoint

curl -L http://127.0.0.1:10250/healthz

Open a bash terminal in a pod

kubectl exec -it storage sh

Check pod environment variables

kubectl exec redis-master-ft9ex env Enable

kubectl shell autocompletion

echo "source <(kubectl completion bash)" »~/.bashrc, and reload

Use minikube dockerd in your laptop

eval $(minikube docker-env), No need to push docker hub any more

Kubectl apply a folder of yaml files

kubectl apply -R -f .

Get services sorted by name

kubectl get services -sort-by=.metadata.name

Get pods sorted by restart count

kubectl get pods -sort-by=’.status.containerStatuses[0].restartCount’

List pods and images

kubectl get pods -o=’custom-columns=PODS:.metadata.name,Images:.spec.containers[*]

List all container images

list-all-images.sh

kubeconfig skip tls verification

skip-tls-verify.md

Ubuntu install kubectl

“deb https://apt.kubernetes.io/ kubernetes-xenial main”

Check Performance

Get node resource usage

kubectl top node

Get pod resource usage

kubectl top pod

Get resource usage for a given pod

kubectl top — containers

List resource utilization for all containers

kubectl top pod — all-namespaces — containers=true

Resources Deletion

Delete pod

kubectl delete pod/<pod_name> -n <my_namespace>

Delete pod by force

kubectl delete pod/<pod_name> — grace-period=0 — force

Delete pods by labels

kubectl delete pod -l env=test

Delete deployments by labels

kubectl delete deployment -l app=wordpress

Delete all resources filtered by labels

kubectl delete pods,services -l name=myLabel

Delete resources under a namespace

kubectl -n my-ns delete po,svc — all

Delete persist volumes by labels

kubectl delete pvc -l app=wordpress

Delete state fulset only (not pods)

kubectl delete sts/<statefull_set_name> — cascade=false

Log & Conf Files

Config folder

/etc/kubernetes/

Certificate files

/etc/kubernetes/pki/

Credentials to API server

/etc/kubernetes/kubelet.conf

Superuser credentials

/etc/kubernetes/admin.conf

kubectl config file

~/.kube/config

Kubernets working dir

/var/lib/kubelet/

Docker working

dir /var/lib/docker/, /var/log/containers/

Etcd working dir

/var/lib/etcd/

Network cni

/etc/cni/net.d/

Log files

/var/log/pods/

log in worker node

/var/log/kubelet.log, /var/log/kube-proxy.log

log in master node

kube-apiserver.log, kube-scheduler.log, kube-controller-manager.log

Env

/etc/systemd/system/kubelet.service.d/10-kubeadm.conf

Env

export KUBECONFIG=/etc/kubernetes/admin.conf

Pod

List all pods

kubectl get pods

List pods for all namespace

kubectl get pods -all-namespaces

List all critical pods

kubectl get -n kube-system pods -a

List pods with more info

kubectl get pod -o wide, kubectl get pod/ <pod_name>-o yaml

Get pod info

kubectl describe pod/srv-mysql-server

List all pods with labels

kubectl get pods — show-labels

List all unhealthy pods

kubectl get pods -field-selector=status.phase!=Running -all-namespaces

List running pods

kubectl get pods -field-selector=status.phase=Running

Get Pod initContainer status

kubectl get pod — template ‘{{.status.initContainerStatuses}}’ <pod_name>

kubectl run command

kubectl exec -it -n “$ns” “$podname” — sh -c “echo $msg »/dev/err.log”

Watch pods

kubectl get pods -n wordpress — watch

Get pod by selector

kubectl get pods -selector=”app=syslog” -o jsonpath=’{.items[*].metadata.name}’

List pods and images

kubectl get pods -o=’custom-columns=PODS:.metadata.name,Images:.spec.containers[*].image’

List pods and containers

-o=’custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name’

Label & Annontation

Filter pods by label

kubectl get pods -l owner=denny

Manually add label to a pod

kubectl label pods dummy-input owner=denny

Remove label

kubectl label pods dummy-input owner

Manually add annonation to a pod

kubectl annotate pods dummy-input my-url=https://dennyzhang.com

Deployment & Scale

Scale out

kubectl scale — replicas=3 deployment/nginx-app

online rolling upgrade

kubectl rollout app-v1 app-v2 — image=img:v2

Roll backup

kubectl rollout app-v1 app-v2 — rollback

List rollout

kubectl get rs

Check update status

kubectl rollout status deployment/nginx-app

Check update history

kubectl rollout history deployment/nginx-app

Pause/Resume

kubectl rollout pause deployment/nginx-deployment, resume

Rollback to previous version

kubectl rollout undo deployment/nginx-deployment

Quota & Limits & Resource

List Resource Quota

kubectl get resourcequota

List Limit Range

kubectl get limitrange

Customize resource definition

kubectl set resources deployment nginx -c=nginx — limits=cpu=200m

Customize resource definition

kubectl set resources deployment nginx -c=nginx — limits=memory=512Mi

Service

List all services

kubectl get services

List service endpoints

kubectl get endpoints

Get service detail

kubectl get service nginx-service -o yaml

Get service cluster ip

kubectl get service nginx-service -o go-template=’{{.spec.clusterIP}}’

Get service cluster port

kubectl get service nginx-service -o go-template=’{{(index .spec.ports 0).port}}’

Expose deployment as lb service

kubectl expose deployment/my-app — type=LoadBalancer — name=my-service

Expose service as lb service

kubectl expose service/wordpress-1-svc — type=LoadBalancer — name=ns1

Secrets

List secrets

kubectl get secrets — all-namespaces

Generate secret

echo -n ‘mypasswd’, then redirect to base64 — decode

Get secret

kubectl get secret denny-cluster-kubeconfig

Get a specific field of a secret

kubectl get secret denny-cluster-kubeconfig -o jsonpath=”{.data.value}”

Create secret from cfg file

kubectl create secret generic db-user-pass -from-file=./username.txt

StatefulSet

List statefulset

kubectl get sts

Delete statefulset only (not pods)

kubectl delete sts/<stateful-set-name> — cascade=false

Scale stateful set

kubectl scale sts/ <stateful-set-name> — replicas=5

Volumes & Volume Claims

List storage class

kubectl get storageclass

Check the mounted volumes

kubectl exec storage ls /data

Check persist volume

kubectl describe pv/pv0001

Copy local file to pod

kubectl cp /tmp/my /:/tmp/server

Copy pod file to local

kubectl cp /:/tmp/server /tmp/my

Events & Metrics

View all events

kubectl get events — all-namespaces

List Events sorted by timestamp

kubectl get events -sort-by=.metadata.creationTimestamp

Node Maintenance

Mark node as unschedulable

kubectl cordon $NODE_NAME

Mark node as schedulable

kubectl uncordon $NODE_NAME

Drain node in preparation for maintenance

kubectl drain $NODE_NAME

Namespace & Security

List authenticated contexts

kubectl config get-contexts, ~/.kube/config

Set namespace preference

kubectl config set-context <context_name> — namespace= <ns_name>

Switch context

kubectl config use-context <cluster_name>

Load context from config file

kubectl get cs — kubeconfig kube_config.yml

Delete the specified context

kubectl config delete-context <cluster_name>

List all namespaces defined

kubectl get namespaces

List certificates

kubectl get csr

Check user privilege

kubectl -as=system:serviceaccount:ns-denny:test-privileged-sa -n ns-denny auth can-i use pods/lis

Check user privilege

kubectl auth can-i use pods/list

Network

Temporarily add a port-forwarding

kubectl port-forward redis-134 6379:6379

Add port-forwaring for deployment

kubectl port-forward deployment/redis-master 6379:6379

Add port-forwaring for replicaset

kubectl port-forward rs/redis-master 6379:6379

Add port-forwaring for service

kubectl port-forward svc/redis-master 6379:6379

Get network policy

kubectl get NetworkPolicy

Extenstions

Enumerates the resource types available

kubectl api-resources

List api group

kubectl api-versions

List all CRD

kubectl get crd

List storageclass

kubectl get storageclass

--

--

Biswanath Giri

Helping students and professionals to learn cloud computing ,google cloud AI/ML and Google Workspace Helping Businesses with their journey to GCP