Skip to content

Kubectl Commands

Configuration and context

Add a new cluster to your kubeconf that supports basic auth

kubectl config set-credentials {{ username }}/{{ cluster_dns }} --username={{ username }} --password={{ password }}

Create new context

kubectl config set-context {{ context_name }} --user={{ username }} --namespace={{ namespace }}

Get current context

kubectl config current-context

List contexts

kubectl config get-contexts

Switch context

kubectl config use-context {{ context_name }}

Creating objects

Create Resource

kubectl create -f {{ resource.definition.yaml | | }} --record

Create a configmap from a file

kubectl create configmap {{ configmap_name }} --from-file {{ path/to/file }}

Deleting resources

Delete the pod using the type and name specified in a file

kubectl delete -f {{ path_to_file }}

Delete pods and services by name

kubectl delete pod,service {{ pod_names }} {{ service_names }}

Delete pods and services by label

kubectl delete pod,services -l {{ label_name }}={{ label_value }}

Delete all pods and services in namespace

kubectl -n {{ namespace_name }} delete po,svc --all

Delete all evicted pods

while read i; do kubectl delete pod "$i"; done < <(kubectl get pods | grep -i evicted | sed 's/ .*//g')

Editing resources

Edit a service

kubectl edit svc/{{ service_name }}

Information gathering

Get credentials

Get credentials

kubectl config view --minify


Restart pods without taking the service down

kubectl rollout deployment {{ deployment_name }}

View status of deployments

kubectl get deployments

Describe Deployments

kubectl describe deployment {{ deployment_name }}

Get images of deployment

kubectl get pods --selector=app={{ deployment_name }} -o json |\
jq '.items[] | + ": " + .spec.containers[0].image'


List all nodes

kubectl get nodes

Check which nodes are ready

JSONPATH='{range .items[*]}{}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
&& kubectl get nodes -o jsonpath=$JSONPATH | grep "Ready=True"

External IPs of all nodes

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

Get exposed ports of node

export NODE_PORT=$(kubectl get services/kubernetes-bootcamp -o go-template='{{(index .spec.ports 0).nodePort}}')


List all pods in the current namespace

kubectl get pods

List all pods in all namespaces

kubectl get pods --all-namespaces

List all pods of a selected namespace

kubectl get pods -n {{ namespace }}

List with more detail

kubectl get pods -o wide

Get pods of a selected deployment

kubectl get pods --selector="name={{ name }}"

Get pods of a given label

kubectl get pods -l {{ label_name }}

Get pods by IP

kubectl get pods -o wide
NAME                               READY     STATUS    RESTARTS   AGE       IP            NODE
alpine-3835730047-ggn2v            1/1       Running   0          5d   ip-10-35-80-221.ec2.internal

Sort pods by restart count

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

Describe Pods

kubectl describe pods {{ pod_name }}

Get name of pod

pod=$(kubectl get pod --selector={{ selector_label }}={{ selector_value }} -o jsonpath={})

List pods that belong to a particular RC

sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
echo $(kubectl get pods --selector=$sel --output=jsonpath={})

Show the remaining space of a persistent volume claim

Either look it in Prometheus or run in the pod that has the PVC mounted:

kubectl -n <namespace> exec <pod-name> -- df -ah

You may need to use kubectl get pod <pod-name> -o yaml to know what volume is mounted where.


List services in namespace

kubectl get services

List services sorted by name

kubectl get services

Describe Services

kubectl describe services {{ service_name }}
kubectl describe svc {{ service_name }}

Replication controller

List all replication controller

kubectl get rc


View status of secrets

kubectl get secrets


View namespaces

kubectl get namespaces


kubectl get limitrange
kubectl describe limitrange limits

Jobs and cronjobs

Get cronjobs of a namespace

kubectl get cronjobs -n {{ namespace }}

Get jobs of a namespace

kubectl get jobs -n {{ namespace }}

You can then describe a specific job to get the pod it created.

kubectl describe job -n {{ namespace }} {{ job_name }}

And now you can see the evolution of the job with:

kubectl logs -n {{ namespace }} {{ pod_name }}

Interacting with nodes and cluster

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 }}

Show metrics of all node

kubectl top node

Show metrics of a node

kubectl top node {{ node_name }}

Display addresses of the master and servies

kubectl cluster-info

Dump current cluster state to stdout

kubectl cluster-info dump

Dump current cluster state to directory

kubectl cluster-info dump --output-directory={{ path_to_directory }}

Interacting with pods

Dump logs of pod

kubectl logs {{ pod_name }}

Dump logs of pod and specified container

kubectl logs {{ pod_name }} -c {{ container_name }}

Stream logs of pod

kubectl logs -f {{ pod_name }}
kubectl logs -f {{ pod_name }} -c {{ container_name }}

Another option is to use the kubetail program.

Attach to running container

kubectl attach {{ pod_name }} -i

Get a shell of a running container

kubectl exec {{ pod_name }} -it bash

Get a debian container inside kubernetes

kubectl run --generator=run-pod/v1 -i --tty debian --image=debian -- bash

Run a pod in a defined node

Get the node hostnames with kubectl get nodes, then override the node with:

kubectl run mypod --image ubuntu:18.04 --overrides='{"apiVersion": "v1", "spec": {"nodeSelector": { "": "my-node.internal" }}}' --command -- sleep 100000000000000

Get a root shell of a running container

  1. Get the Node where the pod is and the docker ID

    kubectl describe pod {{ pod_name }}

  2. SSH into the node

    ssh {{ node }}

  3. Get into docker

    docker exec -it -u root {{ docker_id }} bash

Forward port of pod to your local machine

kubectl port-forward {{ pod_name }} {{ pod_port }}:{{ local_port }}

Expose port

kubectl expose {{ deployment_name }} --type="{{ expose_type }}" --port {{ port_number }}

Where expose_type is one of: ['NodePort', 'ClusterIP', 'LoadBalancer', 'externalName']

Run command on existing pod

kubectl exec {{ pod_name }} -- ls /
kubectl exec {{ pod_name }} -c {{ container_name }} -- ls /

Show metrics for a given pod and it's containers

kubectl top pod {{ pod_name }} --containers

Extract file from pod

kubectl cp {{ container_id }}:{{ path_to_file }} {{ path_to_local_file }}

Scaling resources

Scale a deployment with a specified size

kubectl scale deployment {{ deployment_name }} --replicas {{ replicas_number }}

Scale a replicaset

kubectl scale --replicas={{ replicas_number }} rs/{{ replicaset_name }}

Scale a resource specified in a file

kubectl scale --replicas={{ replicas_number }} -f {{ path_to_yaml }}

Updating resources


Modify the image of a deployment

kubectl set image {{ deployment_name }} {{ label }}:{{ label_value }}
for example
kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1

Or edit it by hand

kubectl edit {{ deployment_name }}

Get the status of the rolling update

kubectl rollout status {{ deployment_name }}

Get the history of the deployment

kubectl rollout history deployment {{ deployment_name }}

To get more details of a selected revision:

kubectl rollout history deployment {{ deployment_name }} --revision={{ revision_number }}

Get back to a specified revision

To get to the last version

kubectl rollout undo deployment {{ deployment_name }}

To go to a specific version

kubectl rollout undo {{ deployment_name }} --to-revision={{ revision_number }}


Rolling update of pods

Is prefered to use the deployment rollout

kubectl rolling-update {{ pod_name }} -f {{ new_pod_definition_yaml }}

Change the name of the resource and update the image

kubectl rolling-update {{ old_pod_name }} {{ new_pod_name }} --image=image:{{ new_pod_version }}

Abort existing rollout in progress

kubectl rolling-update {{ old_pod_name }} {{ new_pod_name }} --rollback

Force replace, delete and then re-create the resource

** Will cause a service outage **

kubectl replace --force -f {{ new_pod_yaml }}

Add a label

kubectl label pods {{ pod_name }} new-label={{ new_label }}

Autoscale a deployment

kubectl autoscale deployment {{ deployment_name }} --min={{ min_instances }} --max={{ max_instances }} [--cpu-percent={{ cpu_percent }}]

Copy resources between namespaces

kubectl get rs,secrets -o json --namespace old | jq '.items[].metadata.namespace = "new"' | kubectl create-f -

Formatting output


Output a JSON formatted API object


Output in the plain-text format with any additional information, and for pods, the node name is included


Output a YAML formatted API object