in

The Essential Kubectl Handbook: Mastering Kubernetes Command-Line Management

Kubectl is the essential command line tool for managing Kubernetes clusters and applications. As Kubernetes has quickly become the standard for container orchestration and microservices, proficiency with kubectl is a must-have skill for any developer, sysadmin or DevOps engineer working with containerized workloads.

This comprehensive handbook will provide you with expert knowledge of kubectl, the Kubernetes command line interface, to effectively manage clusters and ship cloud native applications.

Why Kubectl Matters

Over the last few years, Kubernetes has cemented itself as the leading open-source container orchestration engine. According to the Cloud Native Computing Foundation Survey 2020, 92% of respondents reported using Kubernetes in production – up from 78% in 2019.

The reason for this rapid adoption is that Kubernetes provides a reliable way to deploy, manage and scale containerized applications across clusters of hosts. It radically simplifies many difficult tasks like container networking, storage, rolling updates, autoscaling and more.

But this complexity means Kubernetes itself is complex! Managing clusters requires broad knowledge of concepts like pods, deployments, services, ingress etc. Kubernetes‘ REST API allows managing all these objects declaratively.

This is where kubectl comes in – the official command line interface for interacting with the Kubernetes API. Mastering kubectl is essential for:

  • Deploying applications on Kubernetes.
  • Managing application lifecycles – scaling, upgrades etc.
  • Monitoring and troubleshooting clusters.
  • Automating Kubernetes workflows.

Let‘s look at how kubectl works and how to use it effectively.

Anatomy of kubectl

The kubectl command line tool communicates with the Kubernetes API server to create, inspect, update, and delete Kubernetes objects/resources. The key things to know about using kubectl:

Kubeconfig

To authenticate and access the API server, kubectl uses a configuration file called kubeconfig containing credentials and cluster access details.

Resource Types

Kubernetes has many resource types or API objects, like pods, services, ingress etc, that can be managed via kubectl.

Object Specs

Resources are configured via declarative specs in YAML/JSON called manifests. Kubectl allows CRUD of resources via the manifests.

Convention

kubectl follows a standard convention for CRUD operations:

kubectl [action] [resource] [options]

For example:

kubectl get pods 
kubectl describe nodes

With this background, let‘s look at how to use kubectl effectively.

Setup: Installing kubectl

Kubectl is available on Linux, macOS and Windows. Here are some quick examples to get it installed:

On Linux:

# Download latest binary 
curl -LO https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl

# Make executable
chmod +x ./kubectl

# Move to path
mv ./kubectl /usr/local/bin/kubectl

On macOS:

# Install via Homebrew 
brew install kubectl

On Windows:

Download the latest stable release and then run:

curl -LO https://dl.k8s.io/release/$ENV:stable_version/bin/windows/amd64/kubectl.exe

Refer the Kubernetes docs for other installation options on any OS.

Once installed, verify you can access a cluster:

kubectl version
# Client: shows kubectl version 

kubectl cluster-info 
# Shows Kubernetes master URL

Now let‘s look at some common usage patterns.

Kubectl Basics: Applying, Describing, Deleting

Most kubectl usage involves applying declarative configuration to create or update resources.

For example, create a Pod by applying a YAML manifest:

# pod.yaml
apiVersion: v1
kind: Pod 
metadata:
  name: mypod
spec:
  containers:
  - name: ubuntu  
    image: ubuntu:20.04
    command:
      - sleep
      - "3600"
kubectl apply -f pod.yaml

This will make an API call to create the Pod. You can verify it exists:

kubectl get pods

Output:

NAME    READY   STATUS    RESTARTS   AGE
mypod   1/1     Running   0          10s

To view detailed information about a resource, use kubectl describe:

kubectl describe pod mypod

This will show the Pod manifest plus events, volumes, and other runtime details.

To delete resources, use kubectl delete:

kubectl delete -f pod.yaml
# OR
kubectl delete pod mypod

This covers the basics of applying, inspecting and deleting resources. Now let‘s look at some more usage patterns.

Deploying Applications

The most common Kubernetes workloads are Deployments which maintain a set of identical Pods.

Here is an example Deployment manifest:

# deployment.yaml 

apiVersion: apps/v1
kind: Deployment 
metadata:
  name: myapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp 
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: nginx:1.16
        ports:
        - containerPort: 80

We can create it via:

kubectl apply -f deployment.yaml 

This will create 3 Pods managed by the Deployment. We can verify them:

kubectl get pods

Output:

NAME                    READY   STATUS    RESTARTS   AGE
myapp-5d489d44d-ng7j8   1/1     Running   0          10s    
myapp-5d489d44d-vq9h6   1/1     Running   0          10s
myapp-5d489d44d-vzfbg   1/1     Running   0          10s

We can also check rollout history and status:

kubectl rollout history deployment myapp
kubectl rollout status deployment myapp

This allows us to deploy and manage applications declaratively via kubectl.

Accessing Applications

To expose a Deployment publicly, we create a Service object:

# service.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp 
spec:
  selector:
    app: myapp
  ports:
    - protocol: TCP 
      port: 80
      targetPort: 80 

This will create a service to load balance traffic to the myapp pods on port 80.

We can also create an Ingress to route traffic based on hostname/path:

# ingress.yaml 

apiVersion: networking.k8s.io/v1
kind: Ingress 
metadata:
  name: myapp
spec:
  rules:
  - host: myapp.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: myapp
            port: 
              number: 80

This makes the app accessible at http://myapp.com.

Between Deployments, Services and Ingress, we can get applications deployed and exposed via kubectl.

Managing Application Lifecycles

Kubectl provides controls for common application management tasks:

Scaling

kubectl scale deployment myapp --replicas=5

Upgrades

Set new image for rollout:

kubectl set image deployment myapp *=nginx:1.17

Check rollout status:

kubectl rollout status deployment myapp 

Rollbacks

kubectl rollout undo deployment myapp

These examples demonstrate how kubectl can manage the entire application lifecycle.

Monitoring and Troubleshooting

Kubectl makes it easy to monitor and debug apps:

Get logs

kubectl logs myapp-xyz

Exec into a container

kubectl exec -it myapp-xyz -- sh

Port forward to local machine

kubectl port-forward mypod 5000:5000

Describe objects

kubectl describe pod mypod

These and other kubectl commands are indispensable for monitoring and troubleshooting issues in Kubernetes clusters.

Comparing kubectl to Other Tools

The Kubernetes ecosystem provides other CLI tools that work in conjunction with kubectl:

Tool Description
Helm Package manager for Kubernetes. Allows installing applications from parameterized charts
Kustomize Template-free way to customize Kubernetes manifests via overlays and plugins
Kubeadm Tool for bootstrapping Kubernetes clusters
Kops Simplifies managing production-grade Kubernetes clusters on AWS and other clouds

While kubectl is focused on imperative management of live clusters, these tools help in managing Kubernetes applications (Helm, Kustomize) and infrastructure (Kubeadm, Kops).

Best Practices for kubectl

Here are some tips for getting the most from kubectl:

  • Use YAML rather than JSON for manifests – it‘s easier to read/write
  • Group related objects in labeled directories rather than a huge single YAML
  • Lean on labels to query and organize resources
  • Create aliases for commonly used kubectl commands
  • Use kubectl explain to look up API object definitions
  • Enable shell autocompletion for kubectl
  • Automate complex kubectl workflows using Bash or Ansible

Following best practices like these will enhance your kubectl productivity.

Level Up: Extending kubectl

kubectl provides some powerful advanced features:

Plugins

kubectl is extensible via plugins. For example:

# krew plugin manager
kubectl krew install ctx
kubectl ctx

# handy plugin for interacting with pods  
kubectl plugin install https://github.com/jordanwilson230/kubectl-plugins#kpods

Shell Completion

Enable auto-completion on Bash/Zsh/etc shells via:

source <(kubectl completion bash) # for bash

This makes kubectl faster to use from terminal.

Imperative Commands

In addition to declarative configuration, we can also use kubectl imperatively like so:

kubectl run nginx --image nginx # create deploy

kubectl expose deployment nginx --port=80 # expose service

kubectl scale deploy nginx --replicas=3 # scale

So kubectl offers options for both imperative and declarative management.

Automating and Integrating Kubectl

Since kubectl commands can be executed from scripts, it is easy to automate workflows:

#!/bin/bash

# Rollout new Docker image 
kubectl set image deployment/myapp app=myapp:v2

# Wait for rollout 
kubectl rollout status -w deployment/myapp 

# Update service if changed
kubectl apply -f service.yaml

# Send notification 
curl -X POST https://hooks.slack.com/...

This allows complex deploy and update workflows to be scripted.

Kubectl can also integrate into CI/CD pipelines using Jenkins, CircleCI etc. Changes to manifests in git can trigger automated kubectl apply.

Conclusion

This handbook provided a comprehensive overview of kubectl, including setup, common usage patterns, comparing to other tools, best practices and advanced features.

Kubectl enables declarative management of Kubernetes clusters and applications. Mastering it unlocks the full power of Kubernetes for deploying, operating and automating modern cloud-native infrastructure. The official kubectl reference documentation provides exhaustive information on all available commands.

As Kubernetes continues its meteoric rise, proficiency with kubectl is becoming an essential skill for any technologist working with containers, microservices and modern application architecture. I hope this handbook has provided a solid foundation and springboard for advancing your kubectl skills. Happy Kubectling!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.