DevOps

Mastering Kubernetes: A Comprehensive Cheatsheet

Introduction

Kubernetes, commonly referred to as K8s, is a widely adopted container orchestration platform that simplifies the deployment, scaling, and management of containerized applications.

In the traditional model, deploying applications across different environments posed challenges due to variations in infrastructure and configurations. Kubernetes addresses these challenges by providing a unified platform that abstracts away the complexities of the underlying infrastructure. It allows developers to deploy and manage applications consistently across various environments, fostering portability and scalability.

Kubernetes, like Docker, emphasizes the use of container technology. However, while Docker focuses on packaging and distribution, Kubernetes takes containerization to the next level by providing tools for automating deployment, scaling, and operations.

A Kubernetes cheat sheet is a must-have, providing quick access to essential commands for seamless deployment management. Let’s look at it as your go-to guide in the fast-paced Kubernetes environment, enhancing productivity, minimizing errors, and ensuring efficient navigation through complex tasks.

Kubernetes Basics

Quick Reference Table

The quick reference table below serves as a compass for navigating the terminology crucial to mastering Kubernetes.

TermMeaning
PodSmallest deployable unit in Kubernetes.
NodeA physical or virtual machine in a cluster.
DeploymentDescribes the desired state for a set of pods.
ServiceDefines a set of pods and a policy for accessing them.
LabelsKey-value pairs attached to objects, allowing for flexible categorization and selection. Used for identifying and grouping related resources.
MasterThe control plane in Kubernetes, managing the overall state of the cluster. Components include the API server, etcd, controller manager, and scheduler.
Quick Reference Table

Architecture Overview

Kubernetes operates on a client-server architecture, comprising a control plane and a set of nodes where containers run.

Architecture Overview
Architecture Overview

Essential Commands

With a foundational understanding of terms and architecture, let’s equip ourselves with essential commands for managing Kubernetes clusters. 

These commands are crucial for understanding the status, configuration, and available resources within a Kubernetes cluster. They provide a quick overview of the cluster’s information, version, configuration, available API resources, and versions.

CommandDescription
kubectl cluster-infoDisplay endpoint information about the master and services in the cluster.
kubectl versionDisplay the Kubernetes version running on the client and server.
kubectl config viewGet the configuration of the cluster.
kubectl api-resourcesList the API resources that are available.
kubectl api-versionsList the API versions that are available.
kubectl get all --all-namespacesList everything in all namespaces.
Essential Commands

Pods and Containers

A Pod is the smallest deployable unit in Kubernetes, representing a single instance of a running process in a cluster. Pods are the basic building blocks and can contain one or more containers that share the same network namespace, allowing them to communicate with each other using localhost. 

A Container is a lightweight, standalone, and executable software package that includes everything needed to run a piece of software, including the code, runtime, libraries, and system tools. Containers provide a consistent and isolated environment for applications, ensuring that they run consistently across different environments.

Cheat sheet table: Common commands for creating, managing, and troubleshooting pods

CommandDescription
kubectl apply -f <pod_configuration>Apply the configuration specified in a YAML file to create or update a pod.
kubectl get podsList all pods in the default namespace.
kubectl get pods --all-namespacesList all pods in all namespaces.
kubectl describe pod <pod_name>Display detailed information about a specific pod.
kubectl logs <pod_name>View the logs of a specific pod.
kubectl exec -it <pod_name> -- /bin/bashOpen an interactive shell inside a running container.
kubectl delete pod <pod_name>Delete a specific pod.
kubectl apply -f <pod_configuration>Apply the configuration specified in a YAML file to create or update a pod.
kubectl port-forward <pod_name> <local_port>:<pod_port>Forward ports from a pod to your local machine.
Common Pods Commands

Best practices for effective containerization within the Kubernetes environment

Effective containerization is crucial for smooth application deployment and management in a Kubernetes environment. Here are key best practices to optimize your containerized applications:

  • Adhere to the Single Responsibility Principle, ensuring each container has a specific and well-defined role. This promotes modularity and simplifies maintenance.
  • Minimize the size of your container images by reducing unnecessary layers and dependencies. Smaller images improve deployment speed and reduce resource consumption.
  • Leverage environment variables to configure your application. This enhances flexibility, making it easier to adjust settings without modifying the container image.
  • Implement health probes within your application to enable Kubernetes to assess its health. This helps in automated healing and ensures reliable application performance.
  • Set resource limits, such as CPU and memory, to prevent containers from consuming excessive resources. This ensures fair resource allocation and prevents one misbehaving container from impacting others on the same node.

Code snippets for creating multi-container pods

Using multi-container pods in Kubernetes allows for enhanced collaboration and resource sharing between containers within the same pod. Here are code snippets demonstrating different multi-container patterns.

Sidecar Pattern

The sidecar container runs alongside the main application container, providing additional functionalities without altering the core application.

apiVersion: v1
kind: Pod
metadata:
  name: multi-container-pod
spec:
  containers:
  - name: main-container
    image: main-image:latest
    ports:
    - containerPort: 80
  - name: sidecar-container
    image: sidecar-image:latest

Ambassador Pattern

In this pattern, the ambassador container acts as an intermediary, handling communication and network-related tasks on behalf of the main application.

apiVersion: v1
kind: Pod
metadata:
  name: ambassador-pod
spec:
  containers:
  - name: main-container
    image: main-image:latest
    ports:
    - containerPort: 80
  - name: ambassador-container
    image: ambassador-image:latest
    ports:
    - containerPort: 8080

Adapter Pattern

The adapter container transforms or adapts data before it reaches the main application, providing a seamless integration point.

apiVersion: v1
kind: Pod
metadata:
  name: adapter-pod
spec:
  containers:
  - name: main-container
    image: main-image:latest
    ports:
    - containerPort: 80
  - name: adapter-container
    image: adapter-image:latest
    ports:
    - containerPort: 9090

Deployments and ReplicaSets

Deployments and ReplicaSets are fundamental components in Kubernetes that play an important role in managing the deployment, scaling, and update lifecycle of applications within a cluster. 

A Deployment is a higher-level abstraction in Kubernetes that facilitates the declarative definition of application lifecycles.

A ReplicaSet is closely tied to Deployments and acts as a controller, ensuring a specified number of identical pod replicas are running at all times. 

Visual guide: Lifecycle of Deployments and how ReplicaSets ensure high availability

Deployments in Kubernetes manage the deployment and scaling of pods, providing a declarative approach to defining the desired state. The life cycle involves several key stages:

  • Creation: A Deployment is created with the desired number of replicas and pod template specifications.
  • ReplicaSet Generation: The Deployment creates an associated ReplicaSet, which ensures the specified number of pod replicas are running.
  • Pod Creation: The ReplicaSet creates individual pods based on the defined template.
  • Scaling: Scaling can occur by adjusting the desired number of replicas. The Deployment ensures the correct number of pods are maintained.
  • Rolling Updates: When updating the application, the Deployment creates a new ReplicaSet with the updated configuration while gradually scaling down the old ReplicaSet.
  • Termination: The old ReplicaSet is eventually scaled to zero, and the update is complete.

Cheat sheet for scaling applications with Deployments and managing rolling updates

Scaling Deployments

Scale to a Specific Number of Replicas: kubectl scale deployment <deployment_name> --replicas=<num>

Autoscale Based on CPU Utilization: kubectl autoscale deployment <deployment_name> --cpu-percent=<percentage> --min=<min_replicas> --max=<max_replicas>

Managing Rolling Updates

Update Deployment with a New Image: kubectl set image deployment/<deployment_name> <container_name>=<new_image>

Monitor Rolling Update Progress: kubectl rollout status deployment/<deployment_name>

Rollback to Previous Version: kubectl rollout undo deployment/<deployment_name>

Pause and Resume Rolling Updates: kubectl rollout pause deployment/<deployment_name> and kubectl rollout resume deployment/<deployment_name>

Customize Update Strategy (e.g., Canary Deployment): kubectl apply -f canary-deployment-strategy.yaml

These commands offer a quick reference for scaling deployments to meet demand and efficiently managing rolling updates. Whether adjusting the number of replicas or orchestrating updates with different strategies, this cheat sheet helps streamline the deployment process within a Kubernetes environment.

Code examples for creating and updating ReplicaSets

Creating a ReplicaSet

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: example-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
      - name: app-container
        image: example-image:latest
  • This YAML configuration defines a ReplicaSet named example-replicaset.
  • It specifies that three replicas of the pod should be maintained.
  • The pod template includes a container named app-container using the example-image:latest image.

Updating a ReplicaSet

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: example-replicaset
spec:
  replicas: 5  # Update the number of replicas
  selector:
    matchLabels:
      app: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
      - name: app-container
        image: updated-example-image:latest  # Update the container image
  • This YAML configuration updates the existing ReplicaSet named example-replicaset.
  • It modifies the desired number of replicas to 5.
  • The pod template is updated to use the updated-example-image:latest container image.

Services and Networking

Services define a stable endpoint for accessing a set of pods, while Networking encompasses the mechanisms that enable effective communication between these pods. 

Graphical representation: Kubernetes networking components and their interactions

Kubernetes Networking Components
Kubernetes Networking Components

Cheat sheet for creating and managing Kubernetes services

Creating Services

Create a Service from a YAML file: kubectl apply -f service-definition.yaml

Example service-definition.yaml:

apiVersion: v1
kind: Service
metadata:
  name: example-service
spec:
  selector:
    app: example
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP

Managing Services

List all Services in the default namespace: kubectl get services

Delete a Service: kubectl delete service <service_name>

Expose a Deployment as a Service: kubectl expose deployment <deployment_name> --port=<external_port>

Service Discovery

Discover service details: kubectl describe service <service_name>

Retrieve the ClusterIP of a Service: kubectl get service <service_name> -o jsonpath='{.spec.clusterIP}'

YAML examples for defining Services and exposing applications

ClusterIP Service

apiVersion: v1
kind: Service
metadata:
  name: clusterip-service
spec:
  selector:
    app: example
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP
  • This YAML configuration defines a ClusterIP service named clusterip-service.
  • It selects pods with the label app: example.
  • The service exposes port 80 internally and routes traffic to the pods’ port 8080.

NodePort Service

apiVersion: v1
kind: Service
metadata:
  name: nodeport-service
spec:
  selector:
    app: example
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: NodePort
  • This YAML configuration creates a NodePort service named nodeport-service.
  • It selects pods labeled app: example.
  • The service exposes port 80 on each node, forwarding traffic to the selected pods on port 8080.

LoadBalancer Service

apiVersion: v1
kind: Service
metadata:
  name: loadbalancer-service
spec:
  selector:
    app: example
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer
  • This YAML configuration defines a LoadBalancer service named loadbalancer-service.
  • It selects pods labeled app: example.
  • The service exposes port 80, and in cloud environments, a cloud-specific load balancer is provisioned to distribute traffic to the selected pods.

Configuration and Secrets

ConfigMaps allow central management of non-sensitive configuration details, while Secrets provide a secure mechanism for storing sensitive information such as passwords. 

Key configurations in Kubernetes and practical use cases

ConfigurationUse Case
ConfigMapsCentralized configuration management for applications.
SecretsSecurely store sensitive information like passwords.
Resource LimitsRestrict resource consumption by containers.
Environment VariablesPass configuration details to containers.
Volume MountsShare files and directories between containers and pods.
Labels and AnnotationsMetadata for organizing and querying objects in Kubernetes.
Key Configurations and Use Cases

Secure practices for managing and consuming secrets

  • Use Kubernetes Secrets: Leverage the built-in Kubernetes Secrets API to store sensitive information securely.
  • Encrypt Data in Transit: Ensure that data exchanged between components is encrypted, especially when dealing with sensitive information.
  • Role-Based Access Control (RBAC): Implement RBAC to control access to Secrets, allowing only authorized entities to retrieve sensitive data.
  • Avoid Hardcoding Secrets: Refrain from hardcoding secrets directly in application code or configuration files.
  • Regularly Rotate Secrets: Periodically rotate passwords and cryptographic keys to minimize the impact of a potential security breach.

Code snippets for using ConfigMaps and Secrets in Kubernetes pods

Using ConfigMaps in a Pod

apiVersion: v1
kind: Pod
metadata:
  name: configmap-pod
spec:
  containers:
  - name: app-container
    image: app-image:latest
    envFrom:
    - configMapRef:
        name: example-configmap
  • This YAML configuration defines a pod named configmap-pod.
  • The envFrom field references a ConfigMap named example-configmap.
  • The values from the ConfigMap are injected as environment variables into the pod.

Using Secrets in a Pod

apiVersion: v1
kind: Pod
metadata:
  name: secret-pod
spec:
  containers:
  - name: app-container
    image: app-image:latest
    envFrom:
    - secretRef:
        name: example-secret
  • This YAML configuration creates a pod named secret-pod.
  • The envFrom field references a Secret named example-secret.
  • The values from the Secret are injected as environment variables into the pod.

Creating ConfigMap

kubectl create configmap example-configmap --from-literal=key1=value1 --from-literal=key2=value2

  • This command creates a ConfigMap named example-configmap.
  • It includes key-value pairs (key1=value1 and key2=value2) that can be accessed by pods referencing this ConfigMap.

Monitoring and Troubleshooting

Monitoring and troubleshooting in Kubernetes involve the continuous observation and resolution of issues within a cluster. Monitoring tools like Prometheus, Grafana, and cAdvisor provide insights into cluster health, while troubleshooting involves identifying and addressing common issues in pods, nodes, networking, and services. 

Cheat sheet for troubleshooting common issues in Kubernetes clusters

  • Pod Issues:
    • Check pod logs: kubectl logs <pod_name>
    • Describe pod for detailed info: kubectl describe pod <pod_name>
  • Node Issues:
    • View nodes: kubectl get nodes
    • Check node events: kubectl describe node <node_name>
  • Networking Issues:
    • Inspect network policies: kubectl get networkpolicies
  • Service Issues:
    • Verify service status: kubectl get services
  • Configuration Issues:
    • Check ConfigMaps: kubectl get configmaps
  • Resource Issues:
    • View resource usage: kubectl top nodes or kubectl top pods
  • Cluster Information:
    • Get cluster information: kubectl cluster-info
  • API Resources:
    • List available API resources: kubectl api-resources
  • Version Information:
    • Check Kubernetes version: kubectl version

Visual representation of Kubernetes dashboard components

Kubernetes Dashboard
Kubernetes Dashboard

Advanced Topics

Cheat sheet for Helm charts and efficient package management in Kubernetes

Install Helm: curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash

Add Helm Repository: helm repo add stable https://charts.helm.sh/stable

Install a Helm Chart: helm install my-release stable/<chart_name>

Upgrade a Helm Release: helm upgrade my-release stable/<chart_name>

Uninstall a Helm Release: helm uninstall my-release

Code examples for setting up Persistent Volumes and Persistent Volume Claims

Define Persistent Volume (example-pv.yaml)

apiVersion: v1
kind: PersistentVolume
metadata:
  name: example-pv
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /path/to/host/folder

Defines a Persistent Volume named example-pv with a capacity of 1Gi using a host path.

Create Persistent Volume Claim (example-pvc.yaml)

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: example-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

Creates a Persistent Volume Claim named example-pvc requesting 1Gi storage with ReadWriteOnce access.

Use Persistent Volume Claim in Pod (example-pod.yaml)

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: app-container
    image: app-image:latest
    volumeMounts:
    - mountPath: /app/data
      name: data-volume
  volumes:
  - name: data-volume
    persistentVolumeClaim:
      claimName: example-pvc
  • Defines a Pod named example-pod with a container using the specified image.
  • Mounts a volume (data-volume) using the Persistent Volume Claim (example-pvc).

Additional Commands

For Node Management

Nodes in Kubernetes are the physical or virtual machines that form the cluster’s computing infrastructure. These commands allow users to inspect, label, and manage nodes for optimal cluster performance.

CommandDescription
kubectl get nodesDisplay information about nodes in the cluster.
kubectl describe node <node_name>Show detailed information about a specific node.
kubectl label nodes <node_name> <label>Attach a label to a node for categorization.
kubectl cordon <node_name>Mark a node as unschedulable for maintenance.
kubectl uncordon <node_name>Allow a previously unschedulable node to schedule pods.
kubectl drain <node_name>Safely evict all pods from a node before maintenance.
Node Management Commands

For Namespace Management

Namespaces in Kubernetes are virtual clusters within a physical cluster, providing isolation and organization. These commands facilitate the management of namespaces, enabling users to create and inspect them.

CommandDescription
kubectl get namespacesList all namespaces in the cluster.
kubectl create namespace <namespace_name>Create a new namespace.
kubectl describe namespace <namespace_name>Show details about a specific namespace.
Namespace Management Commands

Service Commands

Services in Kubernetes provide a stable endpoint to access a set of pods. These commands aid in the management of services, allowing users to expose deployments and handle service configurations.

CommandDescription
kubectl get servicesList all services in the default namespace.
kubectl get services --all-namespacesList all services in all namespaces.
kubectl describe service <service_name>Display detailed information about a service.
kubectl expose deployment <deployment_name> --port=<external_port>Expose a deployment as a service.
kubectl delete service <service_name>Delete a specific service.
Service Management Commands

Deployment Commands

Deployments in Kubernetes define the desired state for a set of pods. These commands assist in the management of deployments, allowing users to scale, inspect, and modify deployment configurations.

CommandDescription
kubectl get deploymentsList all deployments in the default namespace.
kubectl get deployments --all-namespacesList all deployments in all namespaces.
kubectl describe deployment <deployment_name>Show details about a specific deployment.
kubectl scale deployment <deployment_name> --replicas=<num>Scale the number of replicas in a deployment.
Deployment Management Commands

In this comprehensive Kubernetes cheat sheet, we’ve delved into fundamental concepts, advanced techniques, and essential commands for efficient cluster management. From basic terminology and architecture to intricate configurations, monitoring, and troubleshooting, this resource serves as a valuable quick reference.

As your next steps, consider applying these learnings in practical scenarios, experimenting with different configurations, and exploring additional Kubernetes features. Stay informed about updates in the Kubernetes ecosystem, continuously refine your skills, and consider contributing to the community.

Resources

These resources cover a wide range of topics and cater to different levels of expertise, helping you deepen your understanding of Kubernetes.

  1. Kubernetes Monitoring
    • Website: Understanding Kubernetes Monitoring
    • A comprehensive guide that covers the basics and advanced concepts of Kubernetes Monitoring
  2. Kubernetes monitoring tools
  3. Kubernetes Logging
    • Website: Kubernetes Logging 101: A Complete Guide
    • The article talks about K8s logging, various logging methods, best practices and tools in an easy to read way. 
  4. Official Kubernetes Documentation
  5. Official Kubernetes Blog
    • Website: Kubernetes Blog
    • Learn all about Kubernetes, be it logging, monitoring, configuring, or anything else.
  6. Kubectl Cheat Sheet
    • Website: kubectl Quick Reference
    • A handy reference for kubectl commands, the primary CLI tool for interacting with Kubernetes clusters.
  7. Kubernetes Patterns
  8. Kubernetes Cheat Sheet by Red Hat
  9. Kubernetes Podcast
  10. Kubernetes Slack Channels and Forums

Ashwini Dave

Ashwini Dave, an accomplished digital marketer specializing in SEO and groundbreaking campaigns. With an MBA in Marketing, she crafts strategic, high-impact results. A tech enthusiast exploring AI and cutting-edge tech, Ashwini seamlessly integrates innovation into her marketing strategies. Outside the digital sphere, she is an avid traveler, finding inspiration in nature's beauty while exploring the world.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button