Skip to content

kubectl

Created: 2020-10-06 09:29:46 -0700 Modified: 2021-07-26 17:15:30 -0700

  • Most commands take the form “kubectl action resource”, e.g. “kubectl get nodes” (reference).
  • Aliases
    • Terminology aliases: kubectl has a lot of built-in “shortnames”, e.g. “rs” for “ReplicaSet”. To see most of these, you can do “kubectl api-resources | less -S” and look at the “shortname” column.
    • Command aliases: If you want a set of reasonable zsh aliases, check this out
  • Architecture
    • There’s a diagram here showing how the control plane and your nodes are all likely running in the cloud. They’re on their own isolated, private network (reference (see step 2)). kubectl itself is running on your client machine, e.g. your own computer that you’re reading this note from. It interfaces with the API server.
    • kubectl proxy: because kubectl is outside of your cluster’s network, you can use “kubectl proxy” to run commands directly on the API server. This works by proxying traffic over a specific port (8001 by default), so it’s not like it’s executing all commands as SSH tunneling would. kubectl is handling authentication for you, so then once you’re proxied in, you can just run something like “curl http://localhost:8001/version”.
      • Apparently people don’t really use “kubectl proxy” outside of learning environments. From what I understand though, kubectl on its own doesn’t expose the entirety of the REST API, so sometimes you want a specific piece of information or functionality that would require proxying.
      • You can also use the proxy to call into your container’s APIs, not just the Kubernetes ones.
  • Help: e.g. “kubectl help get” or “kubectl get —help”
  • Show all “kubectl get”-able resources: “kubectl api-resources”
  • Store the name of a single pod in an environment variable: export POD_NAME=$(kubectl get pods -o go-template —template ‘{{range .items}}{{.metadata.name}}{{“n”}}{{end}}‘)
  • Get the status of almost everything: kubectl get all (gets pods, services, DaemonSets, Deployments, ReplicaSets, HPAs, jobs, and cronjobs, not ingress, ConfigMaps, secrets, etc.)
  • Quickly run a simple Linux shell script in a pod with a single container (reference, reference2): the first reference link shows “high-priority-pod.yml”, which runs an ubuntu container with /bin/sh. The second one is specifically named “getting a shell to a running container”.
  • Troubleshoot
    • Get info about a resource: “kubectl describe deployments OPTIONAL_NAME_PREFIX”
    • Get logs: “kubectl logs PODNAME OPTIONAL_CONTAINER_NAME” (note: the names are _not prefixes; they’re the full names)
    • See resource usage: “kubectl top pods”
    • Execute a command in a container: “kubectl exec POD_NAME OPTIONAL_CONTAINER_NAME COMMAND”
      • Print environment variables: kubectl exec kubernetes-bootcamp-765bf4c7b4-kt25d env
      • Run Bash: kubectl exec -ti $POD_NAME bash