Working with Kubernetes is quite easy, using either a Command Line Interface (CLI) or REST API. in this series, we will be using Kubectl as the kubernetes command line client and we will discover examples how to quickly get started with kubectl and its commands such as get, create, apply, and run.

For this post, I am using AKS (Azure Kubernetes Service) version 1.14.6 and kubectl setup and configured on Azure Cloud Shell.

AKS Documentation: https://docs.microsoft.com/en-us/azure/aks

Azure Cloud Shell: https://docs.microsoft.com/en-us/azure/cloud-shell/overview


Table of contents

  1. Installing kubectl
    1.1 Installing on Ubuntu/Debian
    1.2 Installing on Redhat/Centos
    1.3 Installing on macOS
    1.4 Installing on windows
  2. kubectl and kubernetes version
  3. kubectl Autocomplete
  4. Finding objects information
  5. kubectl create/run/apply
    5.1 Kubectl Create/apply
    5.2 Kubectl run
  6. View and find resources
    6.1 Kubectl Get - Pods/Deployments
    6.2 Kubectl Get - Services
    6.3 Kubectl Get - Nodes


Installing Kubectl

If you are using Azure Cloud shell to manage your AKS cluster Kubectl should be already installed. if you are planning to use it directly on your machine then follow the below:

Installing on Ubuntu/Debian

sudo apt-get update && sudo apt-get install -y apt-transport-https
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list
sudo apt-get update
sudo apt-get install -y kubectl

Installing on Redhat/CentOS

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF
yum install -y kubectl

Installing on macOS

Installing using Curl

#Download Latest release
curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl"

#Make the kubectl binary executable.
chmod +x ./kubectl

#Move the binary in to your PATH.
sudo mv ./kubectl /usr/local/bin/kubectl

#Test to ensure the version you installed is up-to-date:
kubectl version

Installing Using Homebrew

#Run the installation command:
brew install kubectl

# or 
brew install kubernetes-cli

#Test to ensure the version you installed is up-to-date:
kubectl version

Installing on windows

Install Kubectl using Chocolaty Package manager

#To Install Kubectl
choco install kubernetes-cli

#To Upgrade Kubectl
choco upgrade kubernetes-cli

#To Uninstall Kubectl
choco uninstall kubernetes-cli

Manual download and install

#Find the latest stable release from this link
https://storage.googleapis.com/kubernetes-release/release/stable.txt

#download the latest release the below link replacing the version from the above link(in this example it is "v1.16.0")
https://storage.googleapis.com/kubernetes-release/release/v1.16.0/bin/windows/amd64/kubectl.exe

#Copy the downloaded file to a directory of your choice, then add the directory to the path using the below command.
setx path "%PATH%;C:\path\to\directory\"
Back To Top

kubectl and Kubernetes version

Get Kubernetes Version:

mohammed@Azure:~$ kubectl version --short
Client Version: v1.16.0
Server Version: v1.14.6

It shows the kubectl version 1.16.0 and Kubernetes master versions (API Server) version 1.14.6

Get Kubelet version on the nodes:

mohammed@Azure:~$ kubectl get nodes
NAME                       STATUS   ROLES   AGE    VERSION
aks-agentpool-11763719-0   Ready    agent   32d    v1.14.6
aks-agentpool-11763719-1   Ready    agent   3d7h   v1.14.6

The version above refers to kubelet version on the nodes.

Back To Top

kubectl Autocomplete

In Bash or WSL

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

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

Finding objects information

List all supported resource types along with their shortnames

kubectl api-resources -o wide
Back To Top

kubectl Create/Run/Apply


Kubectl Create/Apply

#Create nginx deployment with a single pod from docker hub registry
kubectl create deployment nginx-deployment --image=nginx

#Create a pod from stdin in yaml format

cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000000"
EOF

#Create multiple pods from stdin in yaml format

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000000"
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep-less
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000"
EOF

# Create a pod from a pod yaml manifest file
kubectl create -f pod.yaml

# Create busybox Pod from github yaml file
kubectl create -f  https://raw.githubusercontent.com/mohatb/porthit/master/pod.yaml

#Create an nginx deployment from github yaml file
kubectl apply -f https://raw.githubusercontent.com/mohatb/porthit/master/deployment.yaml

# create resource(s) in all manifest files in dir
kubectl apply -f ./directory/path
Back To Top

Kubectl run

#Create a basic deployment with a single pod
kubectl run nginx --image=nginx

#Create a temp ubuntu pod with bash and will be deleted on exit
kubectl run my-bash --rm --restart=Never -it --image=ubuntu -- bash

#Run nginx deployment with 2 replicas
kubectl run my-nginx --image=nginx --replicas=2

#Run nginx deployment and expose it on port 80 (when --expose is added, the port specified in --port will also be for the service) Also, the created service will have a type of ClusterIP
kubectl run my-nginx --image=nginx --port=80 --expose

#Run nginx deployment and expose service of LoadBalancer Type.
kubectl run my-nginx --image=nginx --replicas=2 --port=80 --expose --service-overrides='{ "spec": { "type": "LoadBalancer" } }'
Back To Top

Viewing and finding resources

Kubectl Get - Pods/Deployments

#List everything (pod, services, daemonsets, replicaset, and deployments)
kubectl get all --all-namespaces

#Get pods in default namespace
kubectl get pods -o wide

#Get pods in all namespaces
kubectl get pods --all-namespaces -o wide

#Get specific pod
kubectl get pod mynginx

#Get pods in yaml format
kubectl get pod nginx-deployment-6dc89bb469-j4mzh -o yaml

#Export pod yaml file without currnt cluster information
kubectl get pods nginx-deployment-6dc89bb469-j4mzh -o yaml --export

#Get pods and show their labels
kubectl get pods --show-labels

#Get pods with a specific labels
kubectl get pods -l app=nginx-deployment

#Get Pods without showing their node
kubectl get pods my-nginx --server-print=false

# List pods Sorted by Restart Count
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

#List pods and sort them by age (old pods first)
kubectl get pods --sort-by=.metadata.creationTimestamp

#Get pods and sort by nodename
kubectl get po -o wide --sort-by=.spec.nodeName

#For each pod, list whether it containers run on a read-only root filesystem or not
kubectl get pods --all-namespaces -o go-template --template='{{range .items}}{{.metadata.name}}{{"\n"}}{{range .spec.containers}}    read-only: {{if .securityContext.readOnlyRootFilesystem}}{{printf "\033[32m%t\033[0m" .securityContext.readOnlyRootFilesystem}} {{else}}{{printf "\033[91m%s\033[0m" "false"}}{{end}} ({{.name}}){{"\n"}}{{end}}{{"\n"}}{{end}}'

#List All Pod Events
kubectl get events --field-selector involvedObject.kind=Pod

#List Events for a specific pod
kubectl get events --field-selector involvedObject.kind=Pod,involvedObject.name=my-nginx --all-namespaces

Back To Top

Kubectl Get - Services

#List all services in the default namespace
kubectl get services

#List services in all namespaces with additional information
kubectl get service --all-namespaces -o wide

#List services sorted by name
kubectl get services --sort-by=.metadata.name

#Get a service with json format
kubectl get myservice hostnames -o json

#Get a service with yaml format
kubectl get myservice hostnames -o json

#List services with custom output
kubectl get service -o=custom-columns=NAME:.metadata.name,IP:.spec.clusterIP,PORT:.spec.ports[*].targetPort,LoadBalancerIP:.status.loadBalancer.ingress[*].ip

#Get all services events
kubectl get events --field-selector involvedObject.kind=Service

kubectl get events --field-selector involvedObject.kind=Service,involvedObject.name=my-nginx --all-namespaces

Back To Top

Kubectl Get - Nodes

#List all nodes wide output
kubectl get nodes -o wide

#List all nodes with labels
kubectl get nodes --show-labels

#List only nodes name
kubectl get nodes --output=jsonpath="{.items[0].metadata.name}"

#List nodes ip addresses
$ kubectl get nodes --output=jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address} {.spec.podCIDR} {"\n"}{end}'

#List nodes with ExternalIP
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name} {.status.addresses[?(@.type=="ExternalIP")].address}{"\n"}'

#List events sorted by timestamp
kubectl get events --sort-by=.metadata.creationTimestamp

#List all nodes events
kubectl get events --field-selector involvedObject.kind=Service,involvedObject.name=my-nginx --all-namespaces

#List events for a specific node
kubectl get events --field-selector involvedObject.kind=Node,involvedObject.name=aks-agentpool-11763719-1

#Get all events that not equal Normal
kubectl get events --field-selector type!=Normal
Back To Top