Kubectl Tips & Tricks

To get familiar with kubectl and improve productivity with its useful commands

For anyone who learns and works with Kubernetes, its CLI kubectl becomes one of the essential tools to know as to interact with the cluster. Kubectl is a command-line tool that is used to communicate with the Kubernetes control plane via a Kubernetes API.

As Kubernetes API is an HTTP REST API, so every operation in Kubernetes is done as an API endpoint and can be executed through an HTTP request to this API endpoint. The main task of kubectl is to carry forward the HTTP requests to the API endpoints.

Thus, kubectl becomes the most important thing to know for Kubernetes. And in this hands-on lab, we will be going through the handiest and most useful kubectl commands to improve the productivity of each and everyone who is using Kubernetes.

We would also like to thank each and every Twitter user who inspired us to convert this tweet into the hands-on lab and gave some wonderful kubectl tips.

Lab with Kubectl

A Kubernetes cluster is required which can be accessed via kubectl.

Cluster Details

  • Check about the cluster nodes status and get some of its information
kubectl get nodes -o wide
kubectl cluster-info

Also alias k='kubectl' is already setup, so you can use also instead of kubectl on the terminal

kubectl api-resources

Get all the api-resources name of a particular namespace with supported (list) verbs and kind

kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n kube-system
  • To know about the permissions for a given service account for a target namespace
kubectl get ns,sa
kubectl auth can-i --list
kubectl -n kube-system auth can-i --list --as system:serviceaccount:kube-system:default

Working with Pods

  • To understand any Kubernetes objects, like for example pods 
kubectl explain pods
  • Now, let’s create an Nginx pod in the default namespace and explore more on kubectl via this pod.
# nginx-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
     app: nginx
spec:
  containers:
  - name: nginx-demo
    image: teamcloudyuga/nginx:alpine
    ports:
    - containerPort: 80
kubectl apply -f nginx-pod.yaml

Know the status of the Nginx pod 

kubectl get pods -o wide

Keep a watch on the pod 

kubectl get pods --watch

Get the details of all the pods along with containers running in the cluster in a JSON format 

kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.namespace}{"/"}{.metadata.name} {.spec.containers[*].image} {.spec.initContainers[*].image} {.spec.ephemeralcontainers[*].image} {"\n"}{end}'

Check the logs of the pod

kubectl logs nginx-pod
kubectl logs -f nginx-pod

check the logs of the existing pods through labels

kubectl logs -l app=nginx

One can also debug running pods with kubectl debug. For more information you can go to https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/

Interact with the nginx pod through kubectl exec

kubectl exec nginx-pod -- ls /
kubectl exec -it nginx-pod -- bin/sh
kubectl apply -f components.yaml

Check the metrics-server pod in the kube-system namespace and wait till it comes in Running state.

kubectl get pods -n kube-system

Check metrics for nodes

kubectl top nodes

Check metrics for pods in default namespace

kubectl top pod --namespace default

Check metrics for all the pods of the cluster sorted by memory.

kubectl top pods --all-namespaces --sort-by='memory'
  • We can also copy files from a running pod to the host and vice-versa
kubectl cp nginx-pod:/usr/share/nginx/html/index.html ./index.html

you will find that index.html is present in the root directory.

  • Now, delete the Nginx pod without any delay
kubectl delete pod nginx-pod --now

Working with Deployments

  • Now, let’s create a deployment to explore deployment with kubectl
# nginx-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deploy
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: teamcloudyuga/nginx:alpine
        ports:
        - containerPort: 80
kubectl apply -f nginx-deploy.yaml
kubectl get pods --selector=app=nginx

To get all the deployments of the cluster in a JSON format

kubectl get deployments -n default -o=json
  • You can also create your own commands with kubectl by using raw outputs
kubectl get --raw=/apis/apps/v1/deployments

To scan all the deployments in the cluster to identify the deployments with failing replicas using raw API, you can also use the below command 

kubectl get –raw=/apis/apps/v1/deployments | jq ‘.items[] | {name: .metadata.name, replicas: .status.replicas, available: (.status.availableReplicas // 0), unavailable: (.status.unavailableReplicas // 0)} | select (.unavailable > 0)’

Let’s check the metrics also using raw API

kubectl get --raw /metrics | less
  • We can also rollout the existing deployment app to a new version by changing its image version and checking its status
kubectl set image deployment/nginx-deploy nginx=nginx:stable
kubectl rollout status deployment nginx-deploy
  • To check the status of the pod with labels and kubectl wait and some conditions 
kubectl wait --for=condition=ready pod -l app=nginx
  • Now, let’s create a new deployment and store it in a YAML file 
kubectl create deployment new-deploy --image=nginx --dry-run=client -o yaml > quick_deploy.yaml

Check quick_deploy.yaml in the root directory. 

ls
  • We can also get all the events of the cluster
kubectl get events --sort-by=".lastTimestamp"

We can also use kubectl patch command to on existing resource to update any particular field

kubectl patch deploy/nginx-deploy --type merge --patch '{"metadata":{"annotations":{"poke":"yes"}}}'

Verify this by using kubectl describe command

kubectl describe deploy nginx-deploy

If you don’t want to use the patch command to annotate the object, then you can use kubectl annotate 

kubectl annotate deploy nginx-deploy foo='bar' 
  • Do port-forwarding of the existing deployment from 30000 local port to 80 pod port
kubectl port-forward deploy/nginx-deploy 30000:80

check with curl on 127.0.0.1:30000

curl 127.0.0.1:30000
  • Now, delete the nginx-deploy deployment with grace-period=0
kubectl delete deployment nginx-deploy --grace-period=0

Creating a Secret

  • We can also create a secret from a file
kubectl create secret generic db-user-pass \
  --from-file=admin=./admin.txt \
  --from-file=password=./password.txt
kubectl get secrets
kubectl get secret db-user-pass -o yaml

To work with different kubectl plugins via krew, you can refer to another blog of ours for this. Also, to know more about how Autoscaling works in Kubernetes, you can refer to this blog.

References

Conclusion

In this blog, we saw many wonderful and useful Kubectl commands to work and use in our daily life.

Join Our Newsletter

Share this article:

Table of Contents