Skip to content

Commands: Kubernetes & OpenShift

kubectl and oc commands: pods, logs, rollouts, contexts, events, builds, cleanup.

Index
  • #kubernetes
  • #openshift
Updated

Also:k8s · kubectl · kube · oc · ocp

23 items

Kubernetes18

Kubernetes: List pods

Safe

Pods with status, restarts, age, pod IP and node. po is the short name for pods; -A for all namespaces, -w to watch.

kubectl get po -n <namespace> -o wide
What each part does
  1. kubectl getlist resources of a type
  2. poshort name for pods (pod and pods work too)
  3. -n <namespace>in this namespace; -A for every namespace
  4. -o wideadd the pod IP, the node and nominated node columns
Example
$ kubectl get po -n shop -o wide
NAME                   READY   STATUS    RESTARTS   AGE   IP            NODE
api-7d9f8c6b5d-2xkqp   1/1     Running   0          3h    10.244.1.17   node-a
api-7d9f8c6b5d-9wz4t   1/1     Running   2          3h    10.244.2.9    node-b

Also known as: kubectl get po · kubectl get pods · list pods · show pods

Kubernetes: List services and their endpoints

Safe

Services with type, cluster IP, external IP, ports and selector, then the pod IPs actually behind each one.

kubectl get svc -n <namespace> -o wide && kubectl get endpointslices -n <namespace>
What each part does
  1. kubectl get svclist services (svc is the short name)
  2. -n <namespace>in this namespace; -A for all
  3. -o wideadd the SELECTOR column: the pod labels the service routes to
  4. &&then, if that worked
  5. kubectl get endpointslicesthe ready pod IPs:ports behind each service (kubectl get ep on older clusters)
Example
$ kubectl get svc -n shop -o wide
NAME   TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE   SELECTOR
api    ClusterIP   10.96.120.15   <none>        80/TCP    3d    app=api

My note No endpoints? The selector matches no ready pods: compare SELECTOR with kubectl get po --show-labels, and check readiness probes.

Also known as: kubectl get svc · kubectl get services · list services · service has no endpoints · kubectl get ep

Kubernetes: Follow logs of a pod

Safe

Stream a pod's logs from the last 200 lines. Add -c <container> for multi-container pods.

kubectl logs -f <pod> -n <namespace> --tail=200
What each part does
  1. kubectl logsprint a container's logs
  2. -ffollow: keep streaming
  3. <pod>the pod (add -c <container> if it has several)
  4. -n <namespace>namespace of the pod
  5. --tail=200start with the last 200 lines
Example
$ kubectl logs -f api-7c9d8b6f4-x2k9p -n shop --tail=200

Also known as: k8s logs · kubectl logs -f · pod logs

Kubernetes: Show logs of the previous crashed container

Safe

Logs from the container instance that just died: the one with the actual error.

kubectl logs <pod> -n <namespace> --previous
What each part does
  1. kubectl logs <pod>print container logs
  2. -n <namespace>namespace of the pod
  3. --previouslogs of the last terminated instance, i.e. the one that crashed, not the restarted one

My note First thing to run on CrashLoopBackOff.

Also known as: CrashLoopBackOff · previous logs · container restarted

Kubernetes: Describe a pod to see events

Safe

Conditions, container states, last termination reason and events at the bottom.

kubectl describe pod <pod> -n <namespace>
What each part does
  1. kubectl describe pod <pod>human-readable details: containers, state, last state, reason, probes, and Events at the bottom
  2. -n <namespace>namespace of the pod

Also known as: ImagePullBackOff · ErrImagePull · Pending · FailedScheduling · OOMKilled

Kubernetes: List recent events sorted by time

Safe

Scheduling failures, probe failures, image pulls, evictions: newest last.

kubectl get events -n <namespace> --sort-by=.lastTimestamp
What each part does
  1. kubectl get eventslist events: scheduling, pulls, probe failures, kills
  2. -n <namespace>in this namespace
  3. --sort-by=.lastTimestampoldest first, newest at the bottom

Also known as: k8s events · Back-off restarting failed container · Readiness probe failed

Kubernetes: Find pods that are not running

Safe

Every pod in the cluster that is Pending, Failed, Succeeded or Unknown.

kubectl get pods -A --field-selector=status.phase!=Running
What each part does
  1. kubectl get podslist pods
  2. -Ain all namespaces
  3. --field-selector=status.phase!=Runningphase is not Running: Pending, Failed, Succeeded, Unknown (CrashLoopBackOff pods are still Running)

Also known as: broken pods · pending pods

Kubernetes: Show pod CPU and memory usage

Safe

Live usage from metrics-server, highest memory first.

kubectl top pod -n <namespace> --sort-by=memory
What each part does
  1. kubectl top podcurrent CPU and memory per pod (needs metrics-server)
  2. -n <namespace>in this namespace
  3. --sort-by=memorybiggest memory users first (or cpu)

Also known as: kubectl top · memory usage · OOMKilled

Kubernetes: Exec into a pod

Safe

Interactive shell inside the pod's (first) container.

kubectl exec -it <pod> -n <namespace> -- sh
What each part does
  1. kubectl execrun a command in a container of a running pod
  2. -itinteractive + terminal
  3. <pod>the pod (add -c <container> if it has several)
  4. -n <namespace>namespace of the pod
  5. -- sheverything after -- is the command to run; use bash if the image has it

Also known as: kubectl exec · shell into pod

Kubernetes: Port-forward to a service

Safe

Reach a ClusterIP service from your laptop on localhost:<local-port>.

kubectl port-forward svc/<service> <local-port>:<remote-port> -n <namespace>
What each part does
  1. kubectl port-forwardtunnel a local port to a pod through the API server
  2. svc/<service>pick a pod behind this service
  3. <local-port>:<remote-port>listen locally on the first, forward to the second
  4. -n <namespace>namespace of the service
Example
$ kubectl port-forward svc/prometheus-operated 9090:9090 -n monitoring
# then open http://localhost:9090

Also known as: port forward · kubectl port-forward · prometheus ui · grafana ui

Kubernetes: Update a deployment image

Caution

Triggers a rolling update to a new image tag.

kubectl set image deployment/<deployment> <container>=<image>:<tag> -n <namespace>
What each part does
  1. kubectl set imagechange the image of containers (starts a rollout)
  2. deployment/<deployment>the deployment
  3. <container>=<image>:<tag>container name in the pod spec = new image
  4. -n <namespace>its namespace

Also known as: kubectl set image · deploy new version

Kubernetes: Watch rollout status

Safe

Blocks until the rollout completes or fails; non-zero exit on timeout (good in CI).

kubectl rollout status deployment/<deployment> -n <namespace> --timeout=5m
What each part does
  1. kubectl rollout statuswait and report until the rollout finishes or fails
  2. deployment/<deployment>the deployment
  3. -n <namespace>its namespace
  4. --timeout=5mgive up (non-zero exit) after 5 minutes; useful in CI

Also known as: rollout status · deployment progress

Kubernetes: Roll back a deployment

Caution

Return to the previous ReplicaSet. Use --to-revision=<n> for a specific one (see rollout history).

kubectl rollout undo deployment/<deployment> -n <namespace>
What each part does
  1. kubectl rollout undogo back to the previous ReplicaSet (add --to-revision=N for a specific one)
  2. deployment/<deployment>the deployment
  3. -n <namespace>its namespace

My note kubectl rollout history deployment/<deployment> shows revisions first.

Also known as: rollback · undo deploy · kubectl rollout undo

Kubernetes: Restart a deployment

Caution

Recreates pods with a rolling restart (picks up new ConfigMap/Secret values).

kubectl rollout restart deployment/<deployment> -n <namespace>
What each part does
  1. kubectl rollout restartrolling restart: new pods replace old ones, no downtime if replicas > 1
  2. deployment/<deployment>the deployment
  3. -n <namespace>its namespace

Also known as: restart pods · rollout restart

Kubernetes: Switch kubeconfig context

Safe

Point kubectl at another cluster. List them with kubectl config get-contexts.

kubectl config use-context <context>
What each part does
  1. kubectl config use-contextmake a context current (cluster + user + namespace)
  2. <context>context name from kubectl config get-contexts

My note Check twice before prod. kubectl config current-context.

Also known as: kubectx · change cluster · kubeconfig

Kubernetes: Set default namespace for current context

Safe

Stop typing -n on every command.

kubectl config set-context --current --namespace=<namespace>
What each part does
  1. kubectl config set-contextchange a context in your kubeconfig
  2. --currentthe context you're using now
  3. --namespace=<namespace>default namespace, so you can drop -n

Also known as: kubens · default namespace

Kubernetes: Delete evicted and failed pods

Destructive

Cleans up Evicted / Error pods left behind after node pressure.

kubectl delete pods -n <namespace> --field-selector=status.phase=Failed
What each part does
  1. kubectl delete podsdelete pods
  2. -n <namespace>in this namespace
  3. --field-selector=status.phase=Failedonly pods in phase Failed (evicted pods are in this phase)

Also known as: Evicted · delete evicted pods · The node was low on resource: ephemeral-storage

Kubernetes: Print environment variables of a pod

Safe

Every env var the running container sees. Without exec access: kubectl set env deploy/<deployment> --list.

kubectl exec <pod> -n <namespace> -- env
What each part does
  1. kubectl exec <pod>run a command in the pod (add -c <container> if it has several)
  2. -n <namespace>namespace of the pod
  3. -- enveverything after -- runs in the container: print all environment variables

My note kubectl set env deploy/<deployment> --list shows what the deployment defines, including which values come from ConfigMaps and Secrets.

Also known as: kubectl print env · pod env vars · kubectl exec env · printenv

OpenShift5

OpenShift: Log in with a token

Safe

Authenticate oc using the token from 'Copy login command' in the web console.

oc login --token=<token> --server=<api-url>
What each part does
  1. oc loginlog in to an OpenShift cluster
  2. --token=<token>API token (web console: your name > Copy login command)
  3. --server=<api-url>API server URL, e.g. https://api.cluster.example.com:6443

Also known as: oc login · Unauthorized · ocp login

OpenShift: Switch project

Safe

Change the default project (namespace). Run oc projects to list them.

oc project <project>
What each part does
  1. oc projectswitch the current project (namespace); with no argument, show the current one
  2. <project>project name

Also known as: oc project · namespace

OpenShift: Follow build logs

Safe

Stream the logs of the latest build of a BuildConfig.

oc logs -f bc/<build-config>
What each part does
  1. oc logs -ffollow logs
  2. bc/<build-config>the latest build of this BuildConfig

Also known as: build logs · s2i

OpenShift: Start a build and follow it

Safe

Trigger a new build and stream its log until it finishes.

oc start-build <build-config> --follow
What each part does
  1. oc start-build <build-config>start a new build from a BuildConfig
  2. --followstream its logs until it finishes

Also known as: oc start-build

OpenShift: Debug a crashing pod with a shell

Safe

Starts a copy of the pod with a shell instead of its entrypoint, so you can poke around.

oc debug pod/<pod>
What each part does
  1. oc debugstart a copy of the pod with the command replaced by a shell, so it doesn't crash
  2. pod/<pod>the pod to copy (also works with deployment/<name> or node/<name>)

My note oc debug node/<node> gives a root shell on a node (chroot /host).

Also known as: CrashLoopBackOff · oc debug

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…