Skip to content

Instantly share code, notes, and snippets.

@joshisa
Forked from mikejoh/kubectl-one-liners.md
Created May 21, 2021 17:09
Show Gist options
  • Save joshisa/34c9aa605061fe464cb2290e80626047 to your computer and use it in GitHub Desktop.
Save joshisa/34c9aa605061fe464cb2290e80626047 to your computer and use it in GitHub Desktop.
Yet another kubectl one-liners

kubectl one-liners

Enable kubectl completion (needs the bash-completion package):

source <(kubectl completion bash)

Dry-run, outputs Service (--expose) and a Deployment in yaml:

kubectl run --image=apache \ 
--port=80 \
--replicas=3 \
--restart='Always' \
--expose \
--requests='cpu=100m,memory=256Mi' \
--limits='cpu=200m,memory=512Mi' \
--labels=app=apache,version=1 \
--dry-run=true \
-o yaml

In a running container run date:

kubectl exec POD -- bash -c "date"
kubectl exec POD -- date
kubectl exec POD date

Remove label this from a pod:

kubectl label pod POD this-

Add label that=thing to a pod:

kubectl label pod POD that=thing

Select pods based on selector across all namespaces:

kubectl get pods --all-namespaces --selector this=label
kubectl get pods --all-namespaces -l this=label

Create a single Pod without a Deployment (--restart=Never) and a ReplicaSet:

kubectl run nginx --image=nginx --restart=Never

Create a single Pod with a Deployment (and a ReplicaSet):

kubectl run nginx --image=nginx --replicas=1

How the --restart flag behaves with kubectl run:

--restart=Never     Creates a single Pod without a Deployment or a ReplicaSet. You can achive this by creating a single Pod manifest and apply it.
--restart=OnFailure Creates a Pod and a Job.
--restart=Always    Default, creates a Deployment and a ReplicaSet object.

Copy file to/from a Pod:

kubectl cp POD:/path/to/file.txt ./file.txt
kubectl $HOME/file.txt POD:/path/to/file.txt

Patch a Deployment with a new image:

kubectl patch deployment nginx -p '{"spec":{"template":{"spec":{"containers":[{ "name":"nginx", "image":"nginx:1.13.1"}]}}}}'

Sort Kubernetes events on creation timestamp:

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

Output the number of Pods foo and skip Pods bar that are running per node:

kubectl get pods -o wide | grep foo | grep Running | grep -v bar | awk '{print $7}' | sort | uniq -c | sort -nr | wc -l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment