Azure Kubernetes Service Cheat Sheet

Thumb

Azure Kubernetes Service Cheat Sheet

Azure Kubernetes Service (AKS) makes it easy to deploy a Kubernetes cluster. It also makes it easier to use since most of the work is done through Azure, such as maintenance and health monitoring. Azure Kubernetes Service is also free; you just pay for the agent nodes with the clusters. An here at CloudInstitute.io goes into more detail about Kubernetes. The following cheat sheet can help you prepare for an exam or interview involving Azure Kubernetes Service.

Since Kubernetes mainly command, the following list is similar to the ones you find on many other cheat sheets. Here we focus on basic commands and kubectl basics. First, we’ll go over the vocabulary, and then we’ll finish with basic commands used in Kubernetes. Of course, these are only the most common commands; therefore, this is not a complete list, as an exhaustive list would be able to fill an entire book.

Start your 30-day FREE TRIAL with CloudInstitute.io to get access to over 200+ courses. 

Basic Commands in Kubernetes Service

Kubectl Alias

Linux

alias k=kubectl

Windows

Set-Alias -Name k -Value kubectl

Cluster Info

  • Get clusters

kubectl config get-clusters

NAME

docker-for-desktop-cluster

foo

  • Get cluster info.

kubectl cluster-info

Kubernetes master is running at https://172.17.0.58:8443

Contexts

A context is a user, cluster, and namespace.

  • Get a list of contexts.

kubectl config get-contexts

CURRENT   NAME                 CLUSTER                      AUTHINFO             NAMESPACE

              docker-desktop       docker-desktop             docker-desktop

*             foo                                foo                            foo                         bar

  • Get the current context.

kubectl config current-context

foo

  • Switch current context.

kubectl config use-context docker-desktop

  • Set default namesapce

kubectl config set-context $(kubectl config current-context) --namespace=my-namespace

You can install/use kubectx to go back and forth between contexts.

Get Commands

kubectl get all

kubectl get namespaces

kubectl get configmaps

kubectl get nodes

kubectl get pods

kubectl get rs

kubectl get svc kuard

kubectl get endpoints kuard

Here are more switches that you can add to the commands above:

  • -o wide - Show more information.
  • --watch or -w - watch for changes.

Namespaces

  • Namespace – Here you’ll retrieve a resource for a namespace.

You can also change the default namespace for the current context, such as follows:

kubectl config set-context $(kubectl config current-context) --namespace=my-namespace

Again, you can install and use kubens to change namespaces.

Labels

  • Get pods showing labels.

kubectl get pods --show-labels

  • Get pods by label.

kubectl get pods -l environment=production,tier!=frontend

Describe Command

kubectl describe nodes [id]

kubectl describe pods [id]

kubectl describe rs [id]

kubectl describe svc kuard [id]

kubectl describe endpoints kuard [id]

Delete Command

kubectl delete nodes [id]

kubectl delete pods [id]

kubectl delete rs [id]

kubectl delete svc kuard [id]

kubectl delete endpoints kuard [id]

You can also force a pod to be deleted.

kubectl delete pod-name --grace-period=0 –force

Create vs Apply

You can use kubectl create in order to make new resources while kubectl apply updates or inserts resources while maintaining any of the changes that were made, such as scaling pods.

  • --record – This will add the command that’s current as an annotation to the resource.
  • --recursive – Here you will look for yaml in the directory that was specified.

Create Pod

Here is how you create a pod:

kubectl run kuard --generator=run-pod/v1 --image=gcr.io/kuar-demo/kuard-amd64:1 --output yaml --export --dry-run > kuard-pod.yml

kubectl apply -f kuard-pod.yml

Logs

  • Get logs.

kubectl logs -l app=kuard

  • Get logs for previously terminated container.

kubectl logs POD_NAME --previous

  • Watch logs in real time.

kubectl attach POD_NAME

  • Copy files from the pod (This will require the tar binary in the container).

kubectl cp POD_NAME:/var/log .

You can also install and use kail.

Port Forward

kubectl port-forward deployment/kuard 8080:8080

Scaling

  • Update replicas.

kubectl scale deployment nginx-deployment --replicas=10

Autoscaling

  • Set autoscaling config.

kubectl autoscale deployment nginx-deployment --min=10 --max=15 --cpu-percent=80

Rollout

  • Get rollout status.

kubectl rollout status deployment/nginx-deployment

Waiting for rollout to finish: 2 out of 3 new replicas have been updated...

deployment "nginx-deployment" successfully rolled out

  • Get rollout history.

kubectl rollout history deployment/nginx-deployment

kubectl rollout history deployment/nginx-deployment --revision=2

  • Undo a rollout.

kubectl rollout undo deployment/nginx-deployment

kubectl rollout undo deployment/nginx-deployment --to-revision=2

  • Pause/resume a rollout

kubectl rollout pause deployment/nginx-deployment

kubectl rollout resume deploy/nginx-deployment

Pod Example

apiVersion: v1

kind: Pod

metadata:

  name: cuda-test

spec:

  containers:

    - name: cuda-test

      image: "k8s.gcr.io/cuda-vector-add:v0.1"

      resources:

        limits:

          nvidia.com/gpu: 1

  nodeSelector:

    accelerator: nvidia-tesla-p100

Deployment Example

apiVersion: apps/v1

kind: Deployment

metadata:

  name: nginx-deployment

  namespace: my-namespace

  labels:

    - environment: production,

    - teir: frontend

  annotations:

    - key1: value1,

    - key2: value2

spec:

  replicas: 3

  selector:

    matchLabels:

      app: nginx

  template:

    metadata:

      labels:

        app: nginx

    spec:

      containers:

      - name: nginx

        image: nginx:1.7.9

        ports:

        - containerPort: 80

Dashboard

  • Enable proxy

kubectl proxy

Get Credentials

az aks get-credentials --resource-group <Resource Group Name> --name <AKS Name>

Show Dashboard

Secure the dashboard like this. Then run:

az aks browse --resource-group <Resource Group Name> --name <AKS Name>

Upgrade

Get updates

az aks get-upgrades --resource-group <Resource Group Name> --name <AKS Name>

Deploy Kubernetes

  • Sign in to Azure Cloud Shell using your Azure account. Use the Bash version of the Cloud Shell.
  • Pick a region name. We’ll pick “east us”. Now let’s run the commands:

REGION_NAME=eastus

RESOURCE_GROUP=aksworkshop

SUBNET_NAME=aks-subnet

VNET_NAME=aks-vnet

You can also use the “echo” command to check values, such as by using “echo $REGION_NAME”

  1. Now we’ll create a new resource group and call it “aksworkshop”. A single resource is easier to clean up after we are all done.

az group create \

    --name $RESOURCE_GROUP \

    --location $REGION_NAME

Configure Networking

There are two network models when deploying an AKS cluster. The models are Azure Container Networking Interface (CNI) and Kubenet networking.

What is Kubenet Networking?

Kubenet is the default networking model where nodes are assigned an IP address from Azure. The IP address is from the virtual network subnet. The Network Address translation is configured to help the pods reach the resources on the Azure virtual network.

What is Azure Container Networking Interface (CNI)?

This is where every pod has an IP address from the subnet for easy access. The IP addresses are unique and therefore thought out beforehand. Now let’s build a virtual network for the AKS cluster.

  1. The first step is to create the virtual network and the subnet along with it. Pods in your cluster will be assigned an IP address in the following subnet. Run the command below to design the virtual network.

az network vnet create \

    --resource-group $RESOURCE_GROUP \

    --location $REGION_NAME \

    --name $VNET_NAME \

    --address-prefixes 10.0.0.0/8 \

    --subnet-name $SUBNET_NAME \

    --subnet-prefixes 10.240.0.0/16

  1. The second step is to find and store the subnet ID in a bash variable. This is shown in the following command:

SUBNET_ID=$(az network vnet subnet show \

    --resource-group $RESOURCE_GROUP \

    --vnet-name $VNET_NAME \

    --name $SUBNET_NAME \

    --query id -o tsv)

Kubectl Commands and Flags

The following commands and flags are useful when using kubectl in Azure Kubernetes.

Kubectl Autocomplete

Bash

source <(kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion package should be installed first.

echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell.

Another way is to use a shorthand alias:

alias k=kubectlcomplete -F __start_kubectl k

ZSH

source <(kubectl completion zsh)  # setup autocomplete in zsh into the current shellecho "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc # add autocomplete permanently to your zsh shell

Kubectl Configuration and Context

This is how you set which Kubernetes cluster kubectl interacts with. It also modified the configuration.

kubectl config view # Show Merged kubeconfig settings. # use multiple kubeconfig files at the same time and view merged configKUBECONFIG=~/.kube/config:~/.kube/kubconfig2  kubectl config view # get the password for the e2e userkubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}' kubectl config view -o jsonpath='{.users[].name}'    # display the first userkubectl config view -o jsonpath='{.users[*].name}'   # get a list of userskubectl config get-contexts                          # display list of contexts kubectl config current-context                       # display the current-contextkubectl config use-context my-cluster-name           # set the default context to my-cluster-name # add a new user to your kubeconf that supports basic authkubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword # permanently save the namespace for all subsequent kubectl commands in that context.kubectl config set-context --current --namespace=ggckad-s2 # set a context utilizing a specific username and namespace.kubectl config set-context gce --user=cluster-admin --namespace=foo \  && kubectl config use-context gce kubectl config unset users.foo                       # delete user foo

Kubectl Apply

In Kubernetes resources, apply manages applications, such as creating and updating resources in a cluster. This is through “kubectl apply”.

Create Objects

With this in mind, here is how to create objects. This can be done through YAML or JSON, as seen below.

kubectl apply -f ./my-manifest.yaml            # create resource(s)kubectl apply -f ./my1.yaml -f ./my2.yaml      # create from multiple fileskubectl apply -f ./dir                         # create resource(s) in all manifest files in dirkubectl apply -f https://git.io/vPieo          # create resource(s) from urlkubectl create deployment nginx --image=nginx  # start a single instance of nginx # create a Job which prints "Hello World"kubectl create job hello --image=busybox -- echo "Hello World"  # create a CronJob that prints "Hello World" every minutekubectl create cronjob hello --image=busybox   --schedule="*/1 * * * *" -- echo "Hello World"     kubectl explain pods                           # get the documentation for pod manifests # Create multiple YAML objects from stdincat <<EOF | kubectl apply -f -apiVersion: v1kind: Podmetadata:  name: busybox-sleepspec:  containers:  - name: busybox    image: busybox    args:    - sleep    - "1000000"---apiVersion: v1kind: Podmetadata:  name: busybox-sleep-lessspec:  containers:  - name: busybox    image: busybox    args:    - sleep    - "1000"EOF # Create a secret with several keyscat <<EOF | kubectl apply -f -apiVersion: v1kind: Secretmetadata:  name: mysecrettype: Opaquedata:  password: $(echo -n "s33msi4" | base64 -w0)  username: $(echo -n "jane" | base64 -w0)EOF

Find and View Resources

# Get commands with basic outputkubectl get services                          # List all services in the namespacekubectl get pods --all-namespaces             # List all pods in all namespaceskubectl get pods -o wide                      # List all pods in the current namespace, with more detailskubectl get deployment my-dep                 # List a particular deploymentkubectl get pods                              # List all pods in the namespacekubectl get pod my-pod -o yaml                # Get a pod's YAML # Describe commands with verbose outputkubectl describe nodes my-nodekubectl describe pods my-pod # List Services Sorted by Namekubectl get services --sort-by=.metadata.name # List pods Sorted by Restart Countkubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # List PersistentVolumes sorted by capacitykubectl get pv --sort-by=.spec.capacity.storage # Get the version label of all pods with label app=cassandrakubectl get pods --selector=app=cassandra -o \  jsonpath='{.items[*].metadata.labels.version}' # Retrieve the value of a key with dots, e.g. 'ca.crt'kubectl get configmap myconfig \  -o jsonpath='{.data.ca\.crt}' # Get all worker nodes (use a selector to exclude results that have a label# named 'node-role.kubernetes.io/master')kubectl get node --selector='!node-role.kubernetes.io/master' # Get all running pods in the namespacekubectl get pods --field-selector=status.phase=Running # Get ExternalIPs of all nodeskubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' # List Names of Pods that belong to Particular RC# "jq" command useful for transformations that are too complex for jsonpath, it can be found at https://stedolan.github.io/jq/sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name}) # Show labels for all pods (or any other Kubernetes object that supports labelling)kubectl get pods --show-labels # Check which nodes are readyJSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \ && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True" # List all Secrets currently in use by a podkubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq # List all containerIDs of initContainer of all pods# Helpful when cleaning up stopped containers, while avoiding removal of initContainers.kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3 # List Events sorted by timestampkubectl get events --sort-by=.metadata.creationTimestamp # Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.kubectl diff -f ./my-manifest.yaml # Produce a period-delimited tree of all keys returned for nodes# Helpful when locating a key within a complex nested JSON structurekubectl get nodes -o json | jq -c 'path(..)|[.[]|tostring]|join(".")' # Produce a period-delimited tree of all keys returned for pods, etckubectl get pods -o json | jq -c 'path(..)|[.[]|tostring]|join(".")'

Updating Resources

kubectl set image deployment/frontend www=image:v2               # Rolling update "www" containers of "frontend" deployment, updating the imagekubectl rollout history deployment/frontend                      # Check the history of deployments including the revision kubectl rollout undo deployment/frontend                         # Rollback to the previous deploymentkubectl rollout undo deployment/frontend --to-revision=2         # Rollback to a specific revisionkubectl rollout status -w deployment/frontend                    # Watch rolling update status of "frontend" deployment until completionkubectl rollout restart deployment/frontend                      # Rolling restart of the "frontend" deployment  cat pod.json | kubectl replace -f -                              # Replace a pod based on the JSON passed into std # Force replace, delete and then re-create the resource. Will cause a service outage.kubectl replace --force -f ./pod.json # Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000kubectl expose rc nginx --port=80 --target-port=8000 # Update a single-container pod's image version (tag) to v4kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - kubectl label pods my-pod new-label=awesome                      # Add a Labelkubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq       # Add an annotationkubectl autoscale deployment foo --min=2 --max=10                # Auto scale a deployment "foo"

Patching Resources

# Partially update a nodekubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # Update a container's image; spec.containers[*].name is required because it's a merge keykubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' # Update a container's image using a json patch with positional arrayskubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]' # Disable a deployment livenessProbe using a json patch with positional arrayskubectl patch deployment valid-deployment  --type json   -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]' # Add a new element to a positional arraykubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'

Editing Resources

kubectl edit svc/docker-registry                      # Edit the service named docker-registryKUBE_EDITOR="nano" kubectl edit svc/docker-registry   # Use an alternative editor

Scaling Resources

kubectl scale --replicas=3 rs/foo                                 # Scale a replicaset named 'foo' to 3kubectl scale --replicas=3 -f foo.yaml                            # Scale a resource specified in "foo.yaml" to 3kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  # If the deployment named mysql's current size is 2, scale mysql to 3kubectl scale --replicas=5 rc/foo rc/bar rc/baz                   # Scale multiple replication controllers

Deleting Resources

kubectl delete -f ./pod.json                                              # Delete a pod using the type and name specified in pod.jsonkubectl delete pod,service baz foo                                        # Delete pods and services with same names "baz" and "foo"kubectl delete pods,services -l name=myLabel                              # Delete pods and services with label name=myLabelkubectl -n my-ns delete pod,svc --all                                      # Delete all pods and services in namespace my-ns,# Delete all pods matching the awk pattern1 or pattern2kubectl get pods  -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs  kubectl delete -n mynamespace pod

Interacting with Running Pods

kubectl logs my-pod                                 # dump pod logs (stdout)kubectl logs -l name=myLabel                        # dump pod logs, with label name=myLabel (stdout)kubectl logs my-pod --previous                      # dump pod logs (stdout) for a previous instantiation of a containerkubectl logs my-pod -c my-container                 # dump pod container logs (stdout, multi-container case)kubectl logs -l name=myLabel -c my-container        # dump pod logs, with label name=myLabel (stdout)kubectl logs my-pod -c my-container --previous      # dump pod container logs (stdout, multi-container case) for a previous instantiation of a containerkubectl logs -f my-pod                              # stream pod logs (stdout)kubectl logs -f my-pod -c my-container              # stream pod container logs (stdout, multi-container case)kubectl logs -f -l name=myLabel --all-containers    # stream all pods logs with label name=myLabel (stdout)kubectl run -i --tty busybox --image=busybox -- sh  # Run pod as interactive shellkubectl run nginx --image=nginx -n mynamespace                                         # Run pod nginx in a specific namespacekubectl run nginx --image=nginx                     # Run pod nginx and write its spec into a file called pod.yaml--dry-run=client -o yaml > pod.yaml kubectl attach my-pod -i                            # Attach to Running Containerkubectl port-forward my-pod 5000:6000               # Listen on port 5000 on the local machine and forward to port 6000 on my-podkubectl exec my-pod -- ls /                         # Run command in existing pod (1 container case)kubectl exec --stdin --tty my-pod -- /bin/sh        # Interactive shell access to a running pod (1 container case) kubectl exec my-pod -c my-container -- ls /         # Run command in existing pod (multi-container case)kubectl top pod POD_NAME --containers               # Show metrics for a given pod and its containers

Interacting with Nodes and Cluster

kubectl cordon my-node                                                # Mark my-node as unschedulablekubectl drain my-node                                                 # Drain my-node in preparation for maintenancekubectl uncordon my-node                                              # Mark my-node as schedulablekubectl top node my-node                                              # Show metrics for a given nodekubectl cluster-info                                                  # Display addresses of the master and serviceskubectl cluster-info dump                                             # Dump current cluster state to stdoutkubectl cluster-info dump --output-directory=/path/to/cluster-state   # Dump current cluster state to /path/to/cluster-state # If a taint with that key and effect already exists, its value is replaced as specified.kubectl taint nodes foo dedicated=special-user:NoSchedul

Azure Kubernetes Courses

We hope you found this short cheat sheet useful. An here at CloudInstitute.io goes into more detail about Kubernetes. Enroll in our Azure Kubernetes Certifications to learn more about our Azure courses.

Previous Post Next Post
Hit button to validate captcha