Kubectl Quick Reference

An easy to find list of (not so) frequently used kubectl commands.

Kube Config

To connect to a cluster, the kubectl coomand uses a kubeconfig file. This is generally expected to be present at ~/.kube/config. However, you can specify the kubeconfig by specifying the KUBECONFIG environment variable.


# create from multiple files
KUBECONFIG=~/.kube/config kubectl apply -f ./my1.yaml -f ./my2.yaml 

Multiple kubeconfigs can be used at the same time as well



kubectl config view


kubectl commands are executed in the default namespace when a namespace is not specified. To specify the namespace, use -n


kubectl get pods -n my-namespace

Use --all-namespaces to query all namespaces


kubectl get pods --all-namespaces


Changes the replica count of a resource.


kubectl scale <resource> <resource-name> --replicas=<new-replicas>


#Scale a deployment
kubectl scale deployment test-deployment --replicas=1 

# Scale a replicaset named 'foo' to 3.
kubectl scale --replicas=3 rs/foo

# Scale a resource identified by type and name specified in "foo.yaml" to 3.
kubectl scale --replicas=3 -f foo.yaml

# If the deployment named mysql's current size is 2, scale mysql to 3.
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql

# Scale multiple replication controllers.
kubectl scale --replicas=5 rc/foo rc/bar rc/baz

# Scale statefulset named 'web' to 3.
kubectl scale --replicas=3 statefulset/web

Port forwarding to services and deployments

A deployment/service running on the cluster can be exposed to the local machine easily by port forwarding it.


kubectl port-forward TYPE/NAME [options] LOCAL_PORT:REMOTE_PORT


# listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment>
kubectl port-forward deploy/my-deployment 5000:6000

# listen on local port 5000 and forward to Service target port with name <my-service-port>
kubectl port-forward svc/my-service 5000:my-service-port

# listen on local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000

# Listen on port 5000 on the local machine and forward to port 6000 on my-pod
kubectl port-forward my-pod 5000:6000

Execute a command

You can run a command in the first pod and first container in Deployment (single or multi-container cases)


kubectl exec deploy/my-deployment -- ls

# Interactive shell access to a running pod (1 container case)
kubectl exec --stdin --tty my-pod -- /bin/sh

# Attach to Running Container
kubectl attach my-pod -i                            


To display logs from a deployment

kubectl logs deploy/my-deployment

Add -f to follow the logs

Create and connect to a pod in a cluster for debugging

Sometimes you need to be able to see what a pod can do, especially if you are debugging RBAC

kubectl run test --image=ubuntu --restart=Never -- sleep 1d
kubectl exec -it test -- /bin/bash

Remove the pod when finished

kubectl delete pod test