Skip to content

Instantly share code, notes, and snippets.

@pataruco
Created February 4, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pataruco/0ece6ed12bc08ad300961b93ba5243c2 to your computer and use it in GitHub Desktop.
Save pataruco/0ece6ed12bc08ad300961b93ba5243c2 to your computer and use it in GitHub Desktop.
Kubernetes

Kubernetes on the command line

brew install kubernetes-cli
kubectl completion -h

bash

## If running Bash 3.2 included with macOS
brew install bash-completion
## or, if running Bash 4.1+
brew install bash-completion@2

zsh

# Plain
if [ $commands[kubectl] ]; then
  source <(kubectl completion zsh)
fi

# Or with Oh-My-Zsh
plugins=(kubectl)

Logs

You can view logs of containers using kubectl logs POD.

  • If the pod contains multiple containers, you have to specify the container with -c CONTAINER.
  • To follow logs use -f.

There is another nice tool, that makes watching logs a lot easier: stern.

brew install stern

It can log multiple pods and containers at the same time and can filter logs entries by regular expressions. Examples:

# Only staging API without health endpoints
stern ".*" --selector app=api -e health

# Only cloudsql proxy of staging API
stern ".*" --selector app=api --container cloudsql-proxy

Multiple clusters

Kubernetes uses the file $HOME/.kube/config to store a list of contexts. Each context consists of a cluster and a user. One context can be active at a time and is used by default with all kubectl commands. If you want to use another context, specify it with --context or switch the active context.

The following commands are useful to change the current context and namespace:

alias ktx='kubectl config use-context'
alias kns='kubectl config set-context $(kubectl config current-context) --namespace'

Note about clusters on Google Cloud Platform: The gcloud command can add new clusters to your config. Just run gcloud container clusters get-credentials cluster --region REGION --project PROJECT.

Other useful stuff

List, describe and restart pods

# List
kubectl get pod

# Describe
kubectl describe pod POD

# In YAML
kubectl get pod POD -o yaml

We usually deploy pods as part of deployments. This means pods are automatically restarted when there are less pods than specified by the deployment. To restart one pod, you can just delete it:

kubectl delete pod POD

Aliases

alias k='kubectl'

Install:

brew install kube-ps1

Configure:

source /usr/local/opt/kube-ps1/share/kube-ps1.sh

# bash
PS1='[\u@\h \W $(kube_ps1)]\$ '

# zsh
PROMPT='$(kube_ps1)'$PROMPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment