---
title: "Kubernetes"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/kubernetes
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Kubernetes

Kubernetes is an open-source container orchestration platform for automating deployment, scaling, and management of containerized applications.

8 Categories24 Sections68 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

KuberneteskubectlContainersOrchestrationCloud NativeK8sContainer OrchestrationCluster Management

[Markdown for AI(opens in a new tab)](/kubernetes/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Containers & Kubernetes](/series/containers--kubernetes)3/7

[PreviousHelm](/cheatsheets/helm)[NextDocker Compose](/cheatsheets/docker-compose)

All posts in this series (7)

Cheatsheets7

1.  [Docker](/cheatsheets/docker)
2.  [Helm](/cheatsheets/helm)
3.  [KubernetesYou are here](/cheatsheets/kubernetes)
4.  [Docker Compose](/cheatsheets/docker-compose)
5.  [Dockerfile](/cheatsheets/dockerfile)
6.  [Docker Swarm](/cheatsheets/docker-swarm)
7.  [kubectl](/cheatsheets/kubectl)

Kubernetes is the de facto standard for container orchestration. It automates deployment, scaling, and management of containerized applications across clusters of machines. Configuration is declarative, and the control plane restarts failed containers on its own.

## [Key features](#key-features)

-   Deploys containers to nodes automatically
-   Restarts failed containers and replaces unhealthy pods
-   Distributes traffic across pod replicas
-   Rolling updates that change application versions without downtime
-   Quotas and limits to control cluster resource use
-   Network policies, RBAC, and secret management
-   DNS-based service discovery with load balancing
-   Persistent and ephemeral storage orchestration

## [Quick start](#quick-start)

**Install kubectl**: Follow the Install and Configure kubectl section.

**Access cluster**: `kubectl cluster-info`

**Create deployment**: `kubectl create deployment web --image=nginx`

**List resources**: `kubectl get pods,svc,deployments`

**Check application status**: `kubectl describe deployment web`

## [Common workflows](#common-workflows)

1.  **Deploy Application**: Create Deployment with image, replicas, and resources
2.  **Expose Service**: Create Service to access pods internally or externally
3.  **Configure Access**: Set up Ingress or LoadBalancer for external traffic
4.  **Monitor Health**: Check pod status, logs, and events regularly
5.  **Update Application**: Use rolling updates or blue-green deployments
6.  **Scale Load**: Adjust replicas manually or enable HPA for automatic scaling
7.  **Debug Issues**: Examine logs, describe resources, execute debugging containers

The sections above cover pod management, deployments, services, storage, RBAC, and cluster operations.

[Getting Started](#category-getting-started)

-   [Kubernetes Basics](#section-kubernetes-basics)
-   [Install and Configure kubectl](#section-kubectl-installation)
-   [Namespaces and Basic Navigation](#section-namespaces-intro)

[Cluster Management](#category-cluster-management)

-   [Cluster Context and Configuration](#section-context-and-config)
-   [Cluster Information and Monitoring](#section-cluster-info-monitoring)
-   [Node and Resource Management](#section-node-management)

[Pod Management](#category-pod-management)

-   [Creating and Listing Pods](#section-pod-creation)
-   [Inspecting and Debugging Pods](#section-pod-inspection)
-   [Deleting and Cleaning Up Pods](#section-pod-deletion)

[Deployment Management](#category-deployment-management)

-   [Creating Deployments](#section-deployment-creation)
-   [Scaling Deployments](#section-deployment-scaling)
-   [Updating and Rolling Back Deployments](#section-deployment-updates)

[Service & Ingress](#category-service-ingress)

-   [Creating Services](#section-service-creation)
-   [Setting up Ingress](#section-ingress-setup)
-   [Port Forwarding and Debugging](#section-port-forwarding)

[Storage Management](#category-storage-management)

-   [Persistent Volumes and Claims](#section-pvc-pv-basics)
-   [Storage Classes and Dynamic Provisioning](#section-storage-class)
-   [Volume Types and EmptyDir](#section-volume-types)

[Security & RBAC](#category-security-rbac)

-   [RBAC Roles and Bindings](#section-rbac-basics)
-   [Network Policies](#section-network-policies)
-   [Secrets and Secret Management](#section-secrets-security)

[Advanced Operations](#category-advanced-operations)

-   [Logging and Debugging](#section-logging-debugging)
-   [JSONPath Queries and Output Formatting](#section-jsonpath-queries)
-   [Dry-Run and Testing Patterns](#section-dry-run-testing)

No commands found

Try adjusting your search term

## Getting Started

Core Kubernetes concepts and initial setup for beginners

### Kubernetes Basics

Introduction to Kubernetes architecture and core concepts

#### Accessibility

Conceptual explanations with clear real-world analogies

#### Best Practices

-   Understand cluster architecture before deploying applications
-   Organize resources using namespaces for multi-team environments
-   Monitor node capacity to prevent resource exhaustion

#### Common Errors

-   **Unable to connect to the server:** Check KUBECONFIG, verify cluster availability with kubectl cluster-info

#### Keywords

kubernetescontainerorchestrationpodsclustersnodesmaster

[Learn more](https://kubernetes.io/docs/concepts/overview/)

#### Understand Kubernetes architecture

Shows your Kubernetes cluster endpoints and components

Code

Terminal window

```
# Kubernetes architecture consists of:# 1. Control Plane (Master): Manages cluster state and decisions# 2. Worker Nodes: Run containerized applications# 3. Pods: Smallest deployable units (wrappers around containers)# 4. Services: Expose pods to network traffic# 5. Storage: Persistent data storage for pods
# Analogy to VMs:# Traditional: Cluster -> Node -> VM -> Application# Kubernetes: Cluster -> Node -> Pod -> Container
# Key resources:# - Pod: Single or multiple containers sharing network# - Deployment: Manages pod replicas# - Service: Network access to pods# - ConfigMap: Configuration data# - PersistentVolume: Storage resources
```

Execution

Terminal window

```
kubectl cluster-info
```

Output

Terminal window

```
Kubernetes control plane is running at https://127.0.0.1:6443CoreDNS is running at https://127.0.0.1:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
```

-   Requires kubectl and KUBECONFIG configured
-   Control plane manages cluster operations
-   Worker nodes run actual workloads

#### Check cluster nodes and capacity

Lists all nodes in your cluster with their status and information

Code

Terminal window

```
# Get list of all nodes in clusterkubectl get nodes
# Get detailed node informationkubectl get nodes -o wide
# View node resource capacities and allocationskubectl top nodes
# Describe specific nodekubectl describe node node-1
```

Execution

Terminal window

```
kubectl get nodes -o wide
```

Output

Terminal window

```
NAME       STATUS   ROLES    AGE   VERSION   INTERNAL-IP   EXTERNAL-IPminikube   Ready    master   10d   v1.24.0   192.168.1.1   <none>
```

-   STATUS Ready means node is healthy and accepting workloads
-   Roles indicate control plane vs worker nodes
-   top requires metrics-server to be installed

#### Verify kubectl installation and context

Verifies kubectl installation and shows active cluster context

Code

Terminal window

```
# Check kubectl versionkubectl version --client
# View current contextkubectl config current-context
# List all available contextskubectl config get-contexts
# Switch to different contextkubectl config use-context docker-desktop
# Get cluster informationkubectl config view
```

Execution

Terminal window

```
kubectl version --client
```

Output

Terminal window

```
Client Version: v1.26.0Kustomize Version: v4.5.4
```

-   Context determines which cluster kubectl connects to
-   KUBECONFIG can contain multiple clusters
-   Switch contexts for multi-cluster environments

### Install and Configure kubectl

Set up kubectl CLI tool and configure cluster access

#### Accessibility

Clear step-by-step installation and configuration instructions

#### Best Practices

-   Install kubectl matching cluster version (±1 minor version)
-   Use kubeconfig file for cluster authentication
-   Enable shell completion for faster CLI navigation

#### Common Errors

-   **unknown command:** Confirm kubectl is in PATH with \`which kubectl\`

#### Keywords

installkubectlsetupkubeconfigcontext

[Learn more](https://kubernetes.io/docs/tasks/tools/)

#### Install kubectl on Linux

Installs kubectl CLI tool required for managing Kubernetes clusters

Code

Terminal window

```
# Download kubectl binarycurl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
# Make it executablechmod +x kubectl
# Move to PATHsudo mv kubectl /usr/local/bin/
# Verify installationkubectl version --client
# Using package manager (Ubuntu/Debian)sudo apt-get updatesudo apt-get install -y kubectl
```

Execution

Terminal window

```
kubectl version --client
```

Output

Terminal window

```
Client Version: v1.26.0Kustomize Version: v4.5.4
```

-   Always download from official Kubernetes release repository
-   Version should be within 1 minor version of cluster API

#### Configure kubectl with cloud clusters

Configures kubectl to access cloud-managed Kubernetes clusters

Code

Terminal window

```
# AWS EKS - Get cluster configaws eks update-kubeconfig --region us-east-1 --name my-cluster
# Google GKE - Get cluster credentialsgcloud container clusters get-credentials my-cluster --zone us-central1-a
# Azure AKS - Get cluster credentialsaz aks get-credentials --resource-group myResourceGroup --name myAKSCluster
# Verify kubectl can access clusterkubectl cluster-info
```

Execution

Terminal window

```
kubectl config view
```

Output

Terminal window

```
apiVersion: v1clusters:- cluster:    server: https://example.com  name: my-clustercontexts:- context:    cluster: my-cluster    user: my-user  name: my-context
```

-   Each cloud provider has specific commands for credential setup
-   Kubeconfig stored in ~/.kube/config by default

#### Set up kubectl shell completion

Enables tab completion for kubectl commands in your shell

Code

Terminal window

```
# Bash completionecho "source <(kubectl completion bash)" >> ~/.bashrcsource ~/.bashrc
# Zsh completionecho "source <(kubectl completion zsh)" >> ~/.zshrcsource ~/.zshrc
# Fish completionkubectl completion fish | source
# Temporary completion (current session)source <(kubectl completion bash)
```

Execution

Terminal window

```
kubectl completion bash
```

Output

Terminal window

```
# bash completion for kubectl_kubectl_complete() { ... }
```

-   Cuts typing for long resource names and flags
-   Available for bash, zsh, fish, and powershell

### Namespaces and Basic Navigation

Organize resources using namespaces and navigate clusters

#### Accessibility

Clear examples of namespace usage and resource organization

#### Best Practices

-   Use namespaces for environment separation (dev, staging, prod)
-   Apply RBAC policies per namespace for security
-   Set default namespace in kubeconfig to reduce flag typing

#### Common Errors

-   **pods not found in default namespace:** Check active namespace with kubectl config view or specify -n flag

#### Keywords

namespaceorganizeisolationmulti-tenant

[Learn more](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/)

#### Explore and create namespaces

Lists and creates Kubernetes namespaces for resource organization

Code

Terminal window

```
# List all namespaceskubectl get namespaces
# Create new namespacekubectl create namespace development
# Create namespace with YAMLkubectl apply -f - <<EOFapiVersion: v1kind: Namespacemetadata:  name: productionEOF
# Get default namespaces# default - for user workloads# kube-system - for system components# kube-public - world-readable resources# kube-node-lease - node heartbeats
```

Execution

Terminal window

```
kubectl get ns
```

Output

Terminal window

```
NAME              STATUS   AGEdefault           Active   10dkube-system       Active   10dkube-public       Active   10dkube-node-lease   Active   10d
```

-   Default namespace is used if not specified
-   Namespaces isolate resources within same cluster
-   Good for multi-team or multi-environment setups

#### Set default namespace and switch between them

Sets default namespace for kubectl commands without -n flag

Code

Terminal window

```
# Set permanent default namespacekubectl config set-context --current --namespace=development
# View current namespacekubectl config view --minify --output=jsonpath='{..namespace}'
# View resources in specific namespacekubectl get pods --namespace=productionkubectl get pods -n production  # short form
# Switch context with different namespacekubectl config use-context dev-context
```

Execution

Terminal window

```
kubectl config set-context --current --namespace=default
```

Output

Terminal window

```
Context "minikube" modified.
```

-   Default context is stored in ~/.kube/config
-   \-n flag overrides default namespace per command

#### View all resources across namespaces

Lists resources across all namespaces for cluster-wide visibility

Code

Terminal window

```
# List pods across all namespaceskubectl get pods --all-namespaceskubectl get pods -A  # short form
# View services across all namespaceskubectl get svc -A
# Get all resources in all namespaceskubectl get all -A
# Describe resource in specific namespacekubectl describe pod my-pod -n production
```

Execution

Terminal window

```
kubectl get pods -A
```

Output

Terminal window

```
NAMESPACE     NAME                             READY   STATUS    RESTARTSdefault       nginx-pod                        1/1     Running   0kube-system   coredns-64897fb6d9-x8z5k         1/1     Running   0production    app-deployment-abc123-xyz789     1/1     Running   1
```

-   \-A flag is equivalent to --all-namespaces
-   Useful for troubleshooting across entire cluster

## Cluster Management

Manage cluster configuration, nodes, resources, and monitoring

### Cluster Context and Configuration

Manage multiple clusters and kubeconfig contexts

#### Accessibility

Clear examples of managing multiple cluster contexts

#### Best Practices

-   Organize kubeconfig for easy context switching
-   Use meaningful names for contexts (e.g., prod-us-east)
-   Limit kubeconfig credentials to necessary clusters

#### Common Errors

-   **current-context is not set:** Set default context with kubectl config use-context

#### Keywords

contextkubeconfigconfigurationclusterauthentication

[Learn more](https://kubernetes.io/docs/tasks/configuration/)

#### Manage kubeconfig contexts and clusters

Shows all available contexts and allows switching between clusters

Code

Terminal window

```
# View all contexts and clusterskubectl config get-contextskubectl config get-clusters
# Get current contextkubectl config current-context
# Switch to different contextkubectl config use-context another-cluster
# Create new contextkubectl config set-context production --cluster=prod-cluster --user=prod-user
# Delete contextkubectl config delete-context old-context
```

Execution

Terminal window

```
kubectl config get-contexts
```

Output

Terminal window

```
CURRENT   NAME              CLUSTER         AUTHINFO        NAMESPACE*         minikube          minikube        minikube        default          docker-desktop    docker-desktop  docker-desktop  default          kind-cluster1     kind-cluster1   kind-cluster1   default
```

-   Context combines cluster, user, and namespace information
-   \* indicates current context

#### Configure cluster authentication

Manually configure cluster, user, and context settings

Code

Terminal window

```
# Set cluster detailskubectl config set-cluster my-cluster \  --server=https://kubernetes.example.com:6443 \  --certificate-authority=/path/to/ca.crt
# Set user authenticationkubectl config set-credentials my-user \  --client-certificate=/path/to/client.crt \  --client-key=/path/to/client.key
# Create context binding user to clusterkubectl config set-context my-context \  --cluster=my-cluster \  --user=my-user \  --namespace=default
# Verify configurationkubectl config view
```

Execution

Terminal window

```
kubectl config view
```

Output

Terminal window

```
apiVersion: v1clusters:- cluster:    server: https://kubernetes.example.com:6443users:- name: my-usercontexts:- context:    cluster: my-cluster    user: my-user
```

-   Certificates can be base64-encoded in kubeconfig
-   kubectl config view shows merged configuration

#### Merge kubeconfig files and manage credentials

Manage multiple kubeconfig files for different clusters

Code

Terminal window

```
# View kubeconfig locationecho $KUBECONFIG
# Merge multiple kubeconfig filesexport KUBECONFIG=~/.kube/config:~/.kube/prod-config:/tmp/temp-configkubectl config view --merge
# Flatten kubeconfig (consolidate into single file)kubectl config view --flatten > ~/.kube/consolidated-config
# Set KUBECONFIG permanentlyecho "export KUBECONFIG=$HOME/.kube/config" >> ~/.bashrc
# Verify current kubeconfigkubectl config view --minify
```

Execution

Terminal window

```
echo $KUBECONFIG
```

Output

Terminal window

```
/home/user/.kube/config
```

-   Multiple KUBECONFIG files are separated by colon (:)
-   Useful for managing dev, staging, and production clusters

### Cluster Information and Monitoring

Monitor cluster health, resources, and component status

#### Accessibility

Clear examples of checking cluster status and node health

#### Best Practices

-   Monitor node capacity regularly to avoid resource exhaustion
-   Keep system components healthy in kube-system namespace
-   Set up resource monitoring with Prometheus or similar

#### Common Errors

-   **metrics not available:** Install metrics-server with kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

#### Keywords

cluster-infomonitoringmetricshealthstatus

[Learn more](https://kubernetes.io/docs/tasks/debug-application-cluster/resource-metrics-pipeline/)

#### Check cluster health and component status

Shows running components and their endpoints

Code

Terminal window

```
# Get cluster informationkubectl cluster-info
# Get system components (requires metrics-server)kubectl get componentstatuses
# Check API server and cluster versionkubectl api-versions
# List all API resources availablekubectl api-resources
# View cluster detailskubectl describe cluster
```

Execution

Terminal window

```
kubectl cluster-info
```

Output

Terminal window

```
Kubernetes control plane is running at https://127.0.0.1:6443CoreDNS is running at https://127.0.0.1:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
```

-   Confirms kubectl can reach the cluster
-   Dump shows more detailed debug information

#### Monitor node resources and health

Shows CPU and memory usage for all cluster nodes

Code

Terminal window

```
# List nodes with resource informationkubectl get nodes --show-labels
# Get node resource usagekubectl top nodes
# Describe specific node for detailskubectl describe node minikube
# Check node logs (requires SSH or specific monitoring)kubectl logs -f -n kube-system --tail=50 <pod-name>
# Get node conditionskubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq .
```

Execution

Terminal window

```
kubectl top nodes
```

Output

Terminal window

```
NAME       CPU(cores)   CPU%   MEMORY(Mi)   MEMORY%minikube   245m         12%    1234Mi       32%
```

-   Requires metrics-server installed for top command
-   CPU in millicores, memory in megabytes

#### Check persistent volume and storage status

Lists persistent storage resources in the cluster

Code

Terminal window

```
# List persistent volumeskubectl get pv
# List persistent volume claimskubectl get pvc --all-namespaces
# Check storage classeskubectl get storageclass
# Describe specific PVkubectl describe pv pv-name
# Check PVC statuskubectl describe pvc pvc-name -n namespace
```

Execution

Terminal window

```
kubectl get pv
```

Output

Terminal window

```
NAME       CAPACITY   ACCESS MODES   RECLAIM   STATUS   CLAIMpv-001     10Gi       RWO            Delete    Bound    ns/pvc-001
```

-   PV is cluster-level, PVC is namespace-level
-   Status should be Bound for normal operation

### Node and Resource Management

Manage cluster nodes, taints, and resource quotas

#### Accessibility

Clear examples of node operations and cordoning

#### Best Practices

-   Drain nodes gracefully before maintenance or removal
-   Use taints for specialized hardware (GPU, high-memory)
-   Set resource quotas to prevent namespace resource hogging

#### Common Errors

-   **cannot drain node, pods without controllers:** Use --force flag to forcefully remove pods (use with caution)

#### Keywords

nodetainttolerationresource-quotadraincordon

[Learn more](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/)

#### Cordon and drain nodes for maintenance

Safely cordons and drains nodes for maintenance

Code

Terminal window

```
# Cordon node (prevent new pods from scheduling)kubectl cordon node-1
# Drain node (evict all pods safely)kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data
# Uncordon node (allow scheduling again)kubectl uncordon node-1
# Check node statuskubectl get nodeskubectl describe node node-1
```

Execution

Terminal window

```
kubectl get nodes
```

Output

Terminal window

```
NAME       STATUS                     ROLES   AGEnode-1     Ready,SchedulingDisabled   <none>  10dnode-2     Ready                      <none>  10d
```

-   SchedulingDisabled status indicates cordoned node
-   Drain evicts pods so they shut down gracefully

#### Add and remove node taints

Adds and removes taints to control pod scheduling

Code

Terminal window

```
# Add taint to node (prevents scheduling unless tolerated)kubectl taint nodes node-1 key=value:NoSchedule
# Add effect types:# NoSchedule - new pods won't be scheduled# NoExecute - existing pods will be evicted# PreferNoSchedule - prefer not to schedule but may
# Remove taint from nodekubectl taint nodes node-1 key=value:NoSchedule-
# View node taintskubectl describe node node-1 | grep Taints
```

Execution

Terminal window

```
kubectl describe node node-1 | grep Taints
```

Output

Terminal window

```
Taints: gpu=true:NoSchedule
```

-   Pods need matching tolerations to schedule on tainted nodes
-   Common for GPU nodes or specialized hardware

#### Set resource quotas and limits per namespace

Sets resource limits for namespaces to prevent overallocation

Code

Terminal window

```
# Create resource quota for namespacekubectl create quota myrquota --hard=pods=10,cpu=3,memory=10Gi -n development
# View resource quotaskubectl get resourcequota -n development
# Describe quota detailskubectl describe resourcequota myrquota -n development
# Create with YAML for more controlkubectl apply -f - <<EOFapiVersion: v1kind: ResourceQuotametadata:  name: compute-quota  namespace: developmentspec:  hard:    requests.cpu: "10"    requests.memory: "20Gi"    limits.cpu: "20"    limits.memory: "40Gi"EOF
```

Execution

Terminal window

```
kubectl get resourcequota -A
```

Output

Terminal window

```
NAMESPACE    NAME         AGE   REQUEST.CPU   REQUESTMEMORYdevelopment  myrquota     5d    500m / 3      2Gi / 10Gi
```

-   Quotas prevent namespace from consuming excessive cluster resources
-   Pods larger than quota cannot be created

## Pod Management

Create, manage, inspect, and debug Kubernetes pods

### Creating and Listing Pods

Create pods imperatively and declaratively, list and filter them

#### Accessibility

Clear examples showing imperative and declarative pod creation

#### Best Practices

-   Use Deployments instead of bare Pods for production
-   Define resource requests and limits on all containers
-   Use labels for organizing and filtering pods

#### Common Errors

-   **pods are forbidden:** Check RBAC permissions with kubectl auth can-i get pods

#### Keywords

podcreaterunyamlmanifest

[Learn more](https://kubernetes.io/docs/concepts/workloads/pods/)

#### Create pods imperatively with kubectl run

Creates pods using imperative kubectl run command

Code

Terminal window

```
# Create simple pod from imagekubectl run nginx-pod --image=nginx
# Create pod with port mappingkubectl run web --image=nginx --port=8080
# Create pod with resource requests/limitskubectl run app --image=myapp --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi
# Create pod with commandkubectl run busybox --image=busybox --command -- sleep 3600
# Create pod in specific namespacekubectl run test-pod --image=alpine -n development
# Create pod and output YAML (dry-run)kubectl run nginx-pod --image=nginx --dry-run=client -o yaml
```

Execution

Terminal window

```
kubectl run test-pod --image=alpine --dry-run=client -o yaml
```

Output

Terminal window

```
apiVersion: v1kind: Podmetadata:  creationTimestamp: null  name: test-podspec:  containers:  - image: alpine    name: test-pod
```

-   Imperative approach is fast for quick testing
-   Use dry-run to preview YAML before creating

#### Create pods declaratively with YAML manifests

Creates pods using declarative YAML manifests

Code

Terminal window

```
# Create pod from YAML filekubectl apply -f pod.yaml
# Create pod from inline YAMLkubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata:  name: web-pod  namespace: default  labels:    app: webspec:  containers:  - name: nginx    image: nginx:latest    ports:    - containerPort: 80    resources:      requests:        cpu: 100m        memory: 128Mi      limits:        cpu: 500m        memory: 512Mi  - name: sidecar    image: busybox    command: ['sleep', '3600']EOF
# Verify pod creationkubectl get pods
```

Execution

Terminal window

```
kubectl get pods
```

Output

Terminal window

```
NAME      READY   STATUS    RESTARTS   AGEweb-pod   2/2     Running   0          2m
```

-   Declarative approach is preferred for reproducibility
-   YAML files can be version controlled
-   Multiple containers can run in same pod

#### List and filter pods

Lists pods with various filtering and output options

Code

Terminal window

```
# List pods in current namespacekubectl get pods
# List pods with detailed infokubectl get pods -o wide
# List pods across all namespaceskubectl get pods -A
# List pods with labelskubectl get pods --show-labels
# Filter pods by labelkubectl get pods -l app=web
# Filter by multiple labelskubectl get pods -l app=web,tier=frontend
# List pods with custom columnskubectl get pods -o custom-columns=NAME:metadata.name,STATUS:status.phase,IP:status.podIP
```

Execution

Terminal window

```
kubectl get pods -o wide
```

Output

Terminal window

```
NAME      STATUS   IP           NODE      NOMINATEDweb-pod   Running  10.244.0.5   minikube  <none>
```

-   Default shows only current namespace
-   \-o flag controls output format (json, yaml, custom-columns)

### Inspecting and Debugging Pods

Describe, view logs, and debug pod issues

#### Accessibility

Clear examples of debugging workflow

#### Best Practices

-   Always check describe and events first when debugging
-   Use logs to find application errors and issues
-   Create debug containers instead of modifying production pods

#### Common Errors

-   **command not found in container:** Check if base image has the command (alpine lacks some utilities)

#### Keywords

describelogseventsdebugtroubleshot

[Learn more](https://kubernetes.io/docs/tasks/debug-application-cluster/)

#### Describe pods and view details

Shows detailed pod information including events and status

Code

Terminal window

```
# Get basic information about podkubectl get pod web-pod
# Get detailed pod informationkubectl describe pod web-pod
# View pod definition in YAMLkubectl get pod web-pod -o yaml
# View pod in JSON formatkubectl get pod web-pod -o json
# Extract specific fields with JSONPathkubectl get pod web-pod -o jsonpath='{.status.phase}'kubectl get pod web-pod -o jsonpath='{.spec.containers[0].image}'
```

Execution

Terminal window

```
kubectl describe pod web-pod
```

Output

Terminal window

```
Name:         web-podNamespace:    defaultStatus:       RunningIP:           10.244.0.5Containers:  nginx:    Image: nginx:latest  State: Running
```

-   describe shows useful events and error messages
-   Events help identify why pods fail to start

#### View pod logs and stream output

Shows container logs for debugging application issues

Code

Terminal window

```
# View logs from podkubectl logs web-pod
# View logs from specific container in multi-container podkubectl logs web-pod -c nginx
# Stream logs in real-timekubectl logs -f web-pod
# View logs from previous container (crashed pods)kubectl logs web-pod --previous
# Show logs with timestampskubectl logs web-pod --timestamps=true
# Tail last 50 lineskubectl logs web-pod --tail=50
# View logs from deployment podskubectl logs -l app=web --max-log-requests=10
```

Execution

Terminal window

```
kubectl logs web-pod --tail=20
```

Output

Terminal window

```
192.168.1.1 - - [28/Feb/2025:10:30:00] "GET / HTTP/1.1" 200 612192.168.1.2 - - [28/Feb/2025:10:30:01] "GET /index.html HTTP/1.1" 200 612
```

-   \-f flag tails logs in real-time like tail -f
-   \--previous shows logs from before container restart

#### Interactive debugging and shell access

Executes commands and provides shell access to running pods

Code

Terminal window

```
# Execute command in running podkubectl exec web-pod -- ls -la
# Get interactive shell in podkubectl exec -it web-pod -- /bin/bashkubectl exec -it web-pod -- /bin/sh
# Execute command in specific containerkubectl exec -it web-pod -c nginx -- /bin/bash
# Run debugging sidecar in podkubectl debug web-pod -it --image=busybox
# Copy files from podkubectl cp web-pod:/var/www/html/index.html ./index.html# Copy files to podkubectl cp ./config.yaml web-pod:/etc/config.yaml
```

Execution

Terminal window

```
kubectl exec -it web-pod -- hostname
```

Output

Terminal window

```
web-pod
```

-   \-i flag keeps stdin open, -t allocates tty
-   Useful for runtime troubleshooting and inspection

### Deleting and Cleaning Up Pods

Delete pods and manage pod lifecycle

#### Accessibility

Clear examples of pod deletion with various options

#### Best Practices

-   Let Deployments manage pod deletion instead of manual deletion
-   Use graceful termination for stateful applications
-   Clean up resources regularly to save cluster resources

#### Common Errors

-   **the server doesn't have a resource type:** Check spelling of resource type (e.g., Pod vs pod)

#### Keywords

deleteremovecleanupterminationgrace-period

[Learn more](https://kubernetes.io/docs/tasks/run-application/delete-stateful-set/)

#### Delete single and multiple pods

Deletes pods from the cluster

Code

Terminal window

```
# Delete single podkubectl delete pod web-pod
# Delete multiple pods by namekubectl delete pod web-pod app-pod db-pod
# Delete all pods in namespacekubectl delete pods --all
# Delete all pods in all namespaceskubectl delete pods -A --all
# Delete with confirmationkubectl delete pod web-pod  # will prompt for confirmation
```

Execution

Terminal window

```
kubectl delete pod web-pod
```

Output

Terminal window

```
pod "web-pod" deleted
```

-   Delete operations are immediate (use graceful termination)
-   Bare pods are not recreated; use Deployments for self-healing

#### Graceful pod termination and force delete

Gracefully terminates pods with shutdown timeout

Code

Terminal window

```
# Delete with grace period (seconds to shutdown cleanly)kubectl delete pod web-pod --grace-period=30
# Force delete immediately (no grace period)kubectl delete pod web-pod --grace-period=0 --force
# Delete using label selectorkubectl delete pods -l app=web
# Delete using field selectorkubectl delete pods --field-selector=status.phase=Failed
# Check termination status during deletionkubectl get pod web-pod --watch
```

Execution

Terminal window

```
kubectl delete pod web-pod --grace-period=10
```

Output

Terminal window

```
pod "web-pod" deleted
```

-   Default grace period is 30 seconds
-   Pod has time to close connections and save state

## Deployment Management

Deploy applications, manage replicas, and perform rolling updates

### Creating Deployments

Create deployments imperatively and declaratively

#### Accessibility

Clear examples of deployment creation with various options

#### Best Practices

-   Use deployments for stateless applications
-   Always define resource requests and limits
-   Include health checks for reliability

#### Common Errors

-   **invalid value for selector:** Make the label selector match the pod labels exactly

#### Keywords

deploymentcreatereplicasselectortemplate

[Learn more](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/)

#### Create deployments imperatively

Creates deployments using imperative kubectl commands

Code

Terminal window

```
# Create deployment from imagekubectl create deployment web --image=nginx
# Create deployment with replicaskubectl create deployment web --image=nginx --replicas=3
# Create deployment and save YAMLkubectl create deployment web --image=nginx --dry-run=client -o yaml > web-deployment.yaml
# Create deployment with portkubectl run web --image=nginx --port=80 --replicas=3
# Verify deployment creationkubectl get deploymentskubectl get pods
```

Execution

Terminal window

```
kubectl create deployment web --image=nginx --replicas=3
```

Output

Terminal window

```
deployment.apps/web created
```

-   create is imperative, while apply is declarative
-   Deployments automatically create ReplicaSet

#### Create deployments with YAML manifests

Creates deployments declaratively with full control

Code

Terminal window

```
# Create deployment from YAMLkubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata:  name: web-deployment  labels:    app: webspec:  replicas: 3  selector:    matchLabels:      app: web  template:    metadata:      labels:        app: web    spec:      containers:      - name: nginx        image: nginx:1.21        ports:        - containerPort: 80        resources:          requests:            cpu: 100m            memory: 128Mi          limits:            cpu: 500m            memory: 512Mi        livenessProbe:          httpGet:            path: /            port: 80          initialDelaySeconds: 30          periodSeconds: 10EOF
# List deploymentskubectl get deployments
```

Execution

Terminal window

```
kubectl get deployments -o wide
```

Output

Terminal window

```
NAME             READY   UP-TO-DATE   AVAILABLE   AGEweb-deployment   3/3     3            3           2m
```

-   YAML approach is reproducible and version-controllable
-   spec.replicas defines number of pod replicas
-   selector must match template labels

#### Create deployments with health checks

Creates deployments with health checks for better reliability

Code

Terminal window

```
# Create deployment with liveness and readiness probeskubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata:  name: app-deploymentspec:  replicas: 2  selector:    matchLabels:      app: app  template:    metadata:      labels:        app: app    spec:      containers:      - name: app        image: myapp:v1        ports:        - containerPort: 8080        livenessProbe:          httpGet:            path: /health            port: 8080          initialDelaySeconds: 10          periodSeconds: 10        readinessProbe:          httpGet:            path: /ready            port: 8080          initialDelaySeconds: 5          periodSeconds: 5EOF
```

Execution

Terminal window

```
kubectl describe deployment app-deployment
```

Output

Terminal window

```
Name:                   app-deploymentReplicas:               2 desired | 2 updated | 2 readyStrategy:               RollingUpdate
```

-   Liveness probe restarts unhealthy containers
-   Readiness probe controls traffic to pods

### Scaling Deployments

Scale deployments up and down dynamically

#### Accessibility

Clear examples of manual and automatic scaling

#### Best Practices

-   Set appropriate min/max replicas to prevent excessive scaling
-   Use HPA for variable load applications (web servers)
-   Monitor metrics to tune autoscaling thresholds

#### Common Errors

-   **unable to compute replica count:** Check that metrics-server is running and reporting metrics

#### Keywords

scalereplicashpaautoscaleload

[Learn more](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/)

#### Manually scale deployments

Scales deployments manually by changing replica count

Code

Terminal window

```
# Get deployment infokubectl get deployments
# Scale deployment to 5 replicaskubectl scale deployment web-deployment --replicas=5
# Scale multiple deploymentskubectl scale deployment web-deployment app-deployment --replicas=3
# Verify scalingkubectl get deploymentskubectl get pods
# Scale down to 0 (stop deployment)kubectl scale deployment web-deployment --replicas=0
```

Execution

Terminal window

```
kubectl scale deployment web-deployment --replicas=5
```

Output

Terminal window

```
deployment.apps/web-deployment scaled
```

-   Scaling is immediate
-   Previous pods will be terminated gracefully

#### Set up horizontal pod autoscaling

Sets up automatic scaling based on metrics

Code

Terminal window

```
# Create HPA imperativelykubectl autoscale deployment web-deployment --min=1 --max=10 --cpu-percent=80
# View HPA statuskubectl get hpa
# Describe HPA detailskubectl describe hpa web-deployment
# Create HPA with YAML for more controlkubectl apply -f - <<EOFapiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata:  name: web-hpaspec:  scaleTargetRef:    apiVersion: apps/v1    kind: Deployment    name: web-deployment  minReplicas: 2  maxReplicas: 10  metrics:  - type: Resource    resource:      name: cpu      target:        type: Utilization        averageUtilization: 80EOF
```

Execution

Terminal window

```
kubectl get hpa
```

Output

Terminal window

```
NAME          REFERENCE                  TARGETS   MINPODS  MAXPODSweb-hpa       Deployment/web-deployment  45%/80%   2        10
```

-   Requires metrics-server for CPU/memory metrics
-   HPA v2 supports custom metrics

#### Monitor scaling events and history

Monitors horizontal pod autoscaling events

Code

Terminal window

```
# Monitor scaling in real-timekubectl get hpa --watch
# Check HPA eventskubectl describe hpa web-hpa
# View scaling historykubectl get events --field-selector involvedObject.name=web-deployment
# Check deployment historykubectl rollout history deployment web-deployment
```

Execution

Terminal window

```
kubectl get hpa --watch
```

Output

Terminal window

```
NAME      REFERENCE             TARGETS   MINPODS  MAXPODS  REPLICAS  AGEweb-hpa   Deployment/web-deploy 88%/80%   2        10       8         3m
```

-   HPA cooldown prevents rapid scaling churn
-   Monitor targets to verify autoscaling behavior

### Updating and Rolling Back Deployments

Update application versions and manage rollouts

#### Accessibility

Clear examples of rolling updates and rollback procedures

#### Best Practices

-   Use image tags (not latest) for tracking versions
-   Test updates in staging before production
-   Keep revision limit to manage history

#### Common Errors

-   **no change:** New image must be different from current (use new tag)

#### Keywords

updaterolloutrollbackstrategyrevision

[Learn more](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#updating-a-deployment)

#### Update deployment images

Updates deployment image to new version

Code

Terminal window

```
# Update image in deploymentkubectl set image deployment/web-deployment nginx=nginx:1.22
# Update multiple containerskubectl set image deployment/app app=myapp:v2 sidecar=sidecar:v1 --record
# Update from filekubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata:  name: web-deploymentspec:  template:    spec:      containers:      - name: nginx        image: nginx:1.22EOF
# Watch rollout progresskubectl rollout status deployment/web-deployment
```

Execution

Terminal window

```
kubectl set image deployment/web-deployment nginx=nginx:1.22
```

Output

Terminal window

```
deployment.apps/web-deployment image updated
```

-   Triggers rolling update by default
-   Old pods are gradually replaced with new version

#### Perform rolling updates and monitor progress

Monitors and controls rolling update process

Code

Terminal window

```
# Apply updated deploymentkubectl apply -f web-deployment.yaml
# Watch rollout statuskubectl rollout status deployment/web-deployment
# Check rollout historykubectl rollout history deployment/web-deployment
# View specific revision detailskubectl rollout history deployment/web-deployment --revision=2
# Pause rollout if issues detectedkubectl rollout pause deployment/web-deployment
# Resume paused rolloutkubectl rollout resume deployment/web-deployment
```

Execution

Terminal window

```
kubectl rollout status deployment/web-deployment
```

Output

Terminal window

```
deployment "web-deployment" successfully rolled out
```

-   Pause allows verification before continuing update
-   History shows all previous revisions

#### Rollback deployments to previous versions

Reverts deployment to previous working version

Code

Terminal window

```
# Rollback to previous revisionkubectl rollout undo deployment/web-deployment
# Rollback to specific revisionkubectl rollout undo deployment/web-deployment --to-revision=2
# Check rollback statuskubectl rollout status deployment/web-deployment
# Verify rollback with describekubectl describe deployment web-deployment
# Check pod images to confirm rollbackkubectl get pods -o wide
```

Execution

Terminal window

```
kubectl rollout undo deployment/web-deployment
```

Output

Terminal window

```
deployment.apps/web-deployment rolled back
```

-   Undo creates new ReplicaSet with old version
-   Useful for quick recovery from bad deployments

## Service & Ingress

Expose applications with Services and Ingress

### Creating Services

Expose pods with ClusterIP, NodePort, and LoadBalancer services

#### Accessibility

Clear examples of different service types

#### Best Practices

-   Use ClusterIP initially, add external access only when needed
-   Avoid NodePort in production; use LoadBalancer or Ingress
-   Use label selectors to control pod membership

#### Common Errors

-   **service not found/no endpoints:** Check selector matches pod labels with kubectl get pods --show-labels

#### Keywords

serviceexposeclusteripnodeportloadbalancer

[Learn more](https://kubernetes.io/docs/concepts/services-networking/service/)

#### Create services imperatively

Creates services to expose deployments within or outside cluster

Code

Terminal window

```
# Expose deployment as ClusterIP servicekubectl expose deployment web-deployment --type=ClusterIP --port=80
# Expose as NodePort servicekubectl expose deployment web-deployment --type=NodePort --port=80 --target-port=8080
# Expose as LoadBalancer servicekubectl expose deployment web-deployment --type=LoadBalancer --port=80
# List created serviceskubectl get svc
# Get service detailskubectl describe svc web-deployment
```

Execution

Terminal window

```
kubectl expose deployment web-deployment --type=ClusterIP --port=80
```

Output

Terminal window

```
service/web-deployment exposed
```

-   ClusterIP: internal only
-   NodePort: accessible on node IP
-   LoadBalancer: managed external IP

#### Create services with YAML

Creates services declaratively with full control

Code

Terminal window

```
# Create ClusterIP servicekubectl apply -f - <<EOFapiVersion: v1kind: Servicemetadata:  name: web-servicespec:  type: ClusterIP  selector:    app: web  ports:  - port: 80    targetPort: 8080    protocol: TCPEOF
# Create NodePort servicekubectl apply -f - <<EOFapiVersion: v1kind: Servicemetadata:  name: web-nodeportspec:  type: NodePort  selector:    app: web  ports:  - port: 80    targetPort: 8080    nodePort: 30080EOF
# Create LoadBalancer servicekubectl apply -f - <<EOFapiVersion: v1kind: Servicemetadata:  name: web-lbspec:  type: LoadBalancer  selector:    app: web  ports:  - port: 80    targetPort: 8080EOF
```

Execution

Terminal window

```
kubectl get svc
```

Output

Terminal window

```
NAME          TYPE        CLUSTER-IP  PORT(S)web-service   ClusterIP   10.0.0.1    80/TCP
```

-   selector determines which pods receive traffic
-   targetPort is container port, port is service port

#### List and inspect services

Lists services and their endpoints

Code

Terminal window

```
# List serviceskubectl get svc
# List in all namespaceskubectl get svc -A
# Get service endpointskubectl get endpoints
# Describe service detailskubectl describe svc web-service
# Get service YAMLkubectl get svc web-service -o yaml
# Watch for external IP (LoadBalancer)kubectl get svc -w
```

Execution

Terminal window

```
kubectl get svc -o wide
```

Output

Terminal window

```
NAME          TYPE       SELECTOR   IP         EXTERNAL-IPweb-service   ClusterIP  app=web    10.0.0.1   <none>
```

-   Endpoints show which pods the service routes to
-   EXTERNAL-IP may take time for LoadBalancer type

### Setting up Ingress

Configure Ingress for HTTP/HTTPS routing

#### Accessibility

Clear examples of Ingress configuration

#### Best Practices

-   Use Ingress for HTTP/HTTPS routing instead of NodePort
-   Enable TLS for production Ingresses
-   Use cert-manager with Let's Encrypt for automatic certificates

#### Common Errors

-   **no ingress controller found:** Install Ingress Controller (nginx, traefik) first

#### Keywords

ingressroutinghostnametlsingress-controller

[Learn more](https://kubernetes.io/docs/concepts/services-networking/ingress/)

#### Create basic Ingress routes

Creates basic Ingress for routing HTTP traffic

Code

Terminal window

```
# Create simple path-based Ingresskubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: Ingressmetadata:  name: web-ingressspec:  rules:  - http:      paths:      - path: /        pathType: Prefix        backend:          service:            name: web-service            port:              number: 80EOF
# List ingresseskubectl get ingress
# Get Ingress IP addresskubectl get ingress -o wide
```

Execution

Terminal window

```
kubectl get ingress
```

Output

Terminal window

```
NAME          CLASS   HOSTS   ADDRESS       PORTSweb-ingress   nginx   *       192.168.1.1   80
```

-   Requires Ingress Controller (nginx, traefik, etc.)
-   Address is Ingress Controller's IP

#### Configure hostname-based routing

Routes different hosts to different services

Code

Terminal window

```
# Create host-based Ingresskubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: Ingressmetadata:  name: web-ingressspec:  rules:  - host: example.com    http:      paths:      - path: /        pathType: Prefix        backend:          service:            name: web-service            port:              number: 80  - host: api.example.com    http:      paths:      - path: /        pathType: Prefix        backend:          service:            name: api-service            port:              number: 8080EOF
```

Execution

Terminal window

```
kubectl describe ingress web-ingress
```

Output

Terminal window

```
Name:             web-ingressRules:  Host            Path Backends  example.com     /    web-service:80  api.example.com /    api-service:8080
```

-   Requires DNS pointing to Ingress IP
-   Multiple rules for VHOST configuration

#### Configure TLS termination with Ingress

Configures HTTPS/TLS termination for Ingress

Code

Terminal window

```
# Create TLS secretkubectl create secret tls web-tls --cert=cert.pem --key=key.pem
# Create Ingress with TLSkubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: Ingressmetadata:  name: web-ingress-tlsspec:  tls:  - hosts:    - example.com      secretName: web-tls  rules:  - host: example.com    http:      paths:      - path: /        pathType: Prefix        backend:          service:            name: web-service            port:              number: 80EOF
# Verify TLS setupkubectl describe ingress web-ingress-tls
```

Execution

Terminal window

```
kubectl get secrets
```

Output

Terminal window

```
NAME       TYPE                DATA   AGEweb-tls    kubernetes.io/tls   2      3m
```

-   TLS certificate stored as Secret
-   Ingress Controller terminates SSL

### Port Forwarding and Debugging

Forward local ports to cluster resources for debugging

#### Accessibility

Clear examples of port forwarding for different scenarios

#### Best Practices

-   Use port-forward for temporary debugging only
-   Use Services for permanent application access
-   Close port-forward when done to free local ports

#### Common Errors

-   **address already in use:** Kill existing process with same port or use different port

#### Keywords

port-forwardlocalhostdebugtesting

[Learn more](https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/)

#### Forward local port to pod

Creates local port forward to pod

Code

Terminal window

```
# Forward local to podkubectl port-forward pod/web-pod 8000:80
# Forward with background processkubectl port-forward pod/web-pod 8000:80 &
# Forward to specific pod in deploymentkubectl port-forward deployment/web-deployment 8000:80
# Forward with address bindingkubectl port-forward pod/web-pod 127.0.0.1:8000:80
# Forward random local portkubectl port-forward pod/web-pod :80
```

Execution

Terminal window

```
kubectl port-forward pod/web-pod 8000:80 &
```

Output

Terminal window

```
Forwarding from 127.0.0.1:8000 -> 80Forwarding from [::1]:8000 -> 80
```

-   Access pod at localhost:8000 from host
-   Useful for testing without exposing service

#### Access services through port forwarding

Forwards to Service which routes to backend pods

Code

Terminal window

```
# Forward to servicekubectl port-forward service/web-service 8000:80
# Forward to service in specific namespacekubectl port-forward -n production service/db-service 5432:5432
# Forward multiple portskubectl port-forward pod/app 8000:8000 8080:8080
# Kill port forward# Use Ctrl+C or kill processps aux | grep port-forwardkill <pid>
```

Execution

Terminal window

```
kubectl port-forward service/web-service 8000:80
```

Output

Terminal window

```
Forwarding from 127.0.0.1:8000 -> 80
```

-   Service provides load balancing across pods
-   Random pod is selected if multiple exist

## Storage Management

Manage persistent storage with volumes and storage classes

### Persistent Volumes and Claims

Create and manage persistent storage

#### Accessibility

Clear examples of PV/PVC creation and binding

#### Best Practices

-   Use StorageClass for dynamic provisioning instead of manual PVs
-   Set appropriate reclaim policies for your use case
-   Monitor storage usage to prevent disk full

#### Common Errors

-   **pod does not have permission to access volume:** Check volume access mode (RWO, RWX) and pod selector

#### Keywords

pvpvcvolumestoragepersistence

[Learn more](https://kubernetes.io/docs/concepts/storage/persistent-volumes/)

#### Create persistent volumes and claims

Creates persistent storage volumes and claims

Code

Terminal window

```
# Create Persistent Volumekubectl apply -f - <<EOFapiVersion: v1kind: PersistentVolumemetadata:  name: pv-001spec:  capacity:    storage: 10Gi  accessModes:    - ReadWriteOnce  persistentVolumeReclaimPolicy: Retain  storageClassName: manual  hostPath:    path: /data/pv-001EOF
# Create Persistent Volume Claimkubectl apply -f - <<EOFapiVersion: v1kind: PersistentVolumeClaimmetadata:  name: pvc-001  namespace: defaultspec:  accessModes:    - ReadWriteOnce  storageClassName: manual  resources:    requests:      storage: 5GiEOF
# List PVs and PVCskubectl get pvkubectl get pvc
```

Execution

Terminal window

```
kubectl get pv,pvc
```

Output

Terminal window

```
NAME     CAPACITY  ACCESSMODES  STATUS   CLAIMpv-001   10Gi      RWO          Bound    default/pvc-001
```

-   PV is cluster resource, PVC is namespace resource
-   Status Bound means PVC successfully claimed PV

#### Use volumes in pod specifications

Mounts persistent volume in pod using PVC

Code

Terminal window

```
# Create pod with PVC volumekubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata:  name: data-appspec:  containers:  - name: app    image: busybox    command: ['sleep', '3600']    volumeMounts:    - name: data-volume      mountPath: /data  volumes:  - name: data-volume    persistentVolumeClaim:      claimName: pvc-001EOF
# Verify PVC is mountedkubectl get pod data-app -o yaml | grep -A5 volumes
```

Execution

Terminal window

```
kubectl describe pod data-app | grep -A5 Mounts
```

Output

Terminal window

```
Mounts:  /data from data-volume (rw)
```

-   mountPath is where volume appears in container
-   Volume must exist or pod will not start

#### Manage storage lifecycle

Manages PV/PVC lifecycle and reclamation policies

Code

Terminal window

```
# Check PVC detailskubectl describe pvc pvc-001
# View PV detailskubectl describe pv pv-001
# Delete PVCkubectl delete pvc pvc-001
# Delete PVkubectl delete pv pv-001
# Check reclaim policy behavior# - Retain: Keep PV after PVC deletion# - Delete: Remove PV after PVC deletion# - Recycle: Clear PV data (deprecated)
```

Execution

Terminal window

```
kubectl describe pvc pvc-001
```

Output

Terminal window

```
Name:          pvc-001Status:        BoundVolume:        pv-001Capacity:      5Gi
```

-   Reclaim policy determines what happens after PVC deletion
-   Retain preserves data for manual recovery

### Storage Classes and Dynamic Provisioning

Use storage classes for dynamic volume provisioning

#### Accessibility

Clear examples of storage class creation and usage

#### Best Practices

-   Use storage classes for dynamic provisioning
-   Set default storage class for convenience
-   Enable volume expansion for flexibility

#### Common Errors

-   **provisioner not found:** Install the cloud provisioner (CSI driver) first

#### Keywords

storageclassprovisionerdynamicdynamic-provisioning

[Learn more](https://kubernetes.io/docs/concepts/storage/storage-classes/)

#### Create and list storage classes

Creates storage classes for automatic volume provisioning

Code

Terminal window

```
# Create storage classkubectl apply -f - <<EOFapiVersion: storage.k8s.io/v1kind: StorageClassmetadata:  name: fast-storageprovisioner: kubernetes.io/aws-ebsparameters:  type: gp3  iops: "3000"  throughput: "125"reclaimPolicy: DeleteallowVolumeExpansion: trueEOF
# List storage classeskubectl get storageclass
# Set default storage classkubectl patch storageclass fast-storage -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
```

Execution

Terminal window

```
kubectl get storageclass
```

Output

Terminal window

```
NAME           PROVISIONER             RECLAIMPOLICYfast-storage   kubernetes.io/aws-ebs   Delete
```

-   Provisioner depends on cloud provider
-   Parameters vary by provisioner

#### Use storage class in PVC

Automatically provisions PV when PVC is created

Code

Terminal window

```
# Create PVC using storage classkubectl apply -f - <<EOFapiVersion: v1kind: PersistentVolumeClaimmetadata:  name: app-storagespec:  accessModes:    - ReadWriteOnce  storageClassName: fast-storage  resources:    requests:      storage: 50GiEOF
# Monitor dynamic PV creationkubectl get pv -w
```

Execution

Terminal window

```
kubectl get pvc
```

Output

Terminal window

```
NAME          STATUS   VOLUME         CAPACITYapp-storage   Bound    pvc-abc123     50Gi
```

-   Storage class provisioner automatically creates PV
-   No need to manually create PV first

#### Expand persistent volumes

Expands PVC size without downtime

Code

Terminal window

```
# Edit PVC to increase sizekubectl patch pvc app-storage -p '{"spec":{"resources":{"requests":{"storage":"100Gi"}}}}'
# Or edit directlykubectl edit pvc app-storage
# Monitor expansion progresskubectl describe pvc app-storage
# Verify expansion in podkubectl exec -it <pod> -- df /data
```

Execution

Terminal window

```
kubectl describe pvc app-storage
```

Output

Terminal window

```
Name:          app-storageCapacity:      100Gi
```

-   allowVolumeExpansion must be true in StorageClass
-   Some filesystems require filesystem expansion in pod

### Volume Types and EmptyDir

Use different volume types for various scenarios

#### Accessibility

Clear examples of different volume mount types

#### Best Practices

-   Use ConfigMap/Secret volumes for configuration
-   Use emptyDir for temporary pod data
-   Avoid hostPath in production (not portable)

#### Common Errors

-   **volume not found:** Verify the ConfigMap or Secret exists under the name referenced

#### Keywords

volumeemptydirconfigmapsecrethostpath

[Learn more](https://kubernetes.io/docs/concepts/storage/volumes/)

#### Use emptyDir and hostPath volumes

Uses emptyDir for temporary storage and hostPath for node access

Code

Terminal window

```
# Create pod with emptyDir and hostPathkubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata:  name: app-with-volumesspec:  containers:  - name: app    image: nginx    volumeMounts:    - name: cache      mountPath: /cache    - name: host-data      mountPath: /host-data  volumes:  - name: cache    emptyDir: {}  - name: host-data    hostPath:      path: /data      type: DirectoryEOF
```

Execution

Terminal window

```
kubectl get pod app-with-volumes -o yaml
```

Output

Terminal window

```
volumes:- name: cache  emptyDir: {}
```

-   emptyDir deleted when pod terminates
-   hostPath accesses node filesystem

#### Mount ConfigMaps and Secrets as volumes

Mounts ConfigMaps and Secrets as volumes

Code

Terminal window

```
# Create ConfigMapkubectl create configmap app-config --from-literal=key1=value1
# Create Secretkubectl create secret generic app-secret --from-literal=password=secret
# Create pod mounting bothkubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata:  name: app-with-configspec:  containers:  - name: app    image: busybox    command: ['sleep', '3600']    volumeMounts:    - name: config      mountPath: /etc/config    - name: secret      mountPath: /etc/secrets  volumes:  - name: config    configMap:      name: app-config  - name: secret    secret:      secretName: app-secretEOF
```

Execution

Terminal window

```
kubectl get configmap,secret
```

Output

Terminal window

```
NAME                 DATA   AGEconfigmap/app-config 1      2m
```

-   ConfigMap/Secret updates appear in mounted files
-   Good for configuration without pod restart

## Security & RBAC

Secure cluster with authentication, authorization, and policies

### RBAC Roles and Bindings

Control access with Roles and RoleBindings

#### Accessibility

Clear examples of RBAC configuration

#### Best Practices

-   Follow least privilege principle (minimum needed permissions)
-   Use namespace-scoped Roles instead of ClusterRole when possible
-   Regularly audit and review RBAC configuration

#### Common Errors

-   **forbidden - user cannot get pods:** Create appropriate Role/RoleBinding for the user

#### Keywords

rbacrolerolebindingserviceaccountpermission

[Learn more](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)

#### Create RBAC roles and bindings

Creates RBAC roles and grants permissions to service accounts

Code

Terminal window

```
# Create service accountkubectl create serviceaccount app-sa -n development
# Create role with permissionskubectl apply -f - <<EOFapiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata:  name: pod-reader  namespace: developmentrules:- apiGroups: [""]  resources: ["pods"]  verbs: ["get", "list", "watch"]- apiGroups: [""]  resources: ["pods/logs"]  verbs: ["get"]EOF
# Create role bindingkubectl apply -f - <<EOFapiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata:  name: pod-reader-binding  namespace: developmentroleRef:  apiGroup: rbac.authorization.k8s.io  kind: Role  name: pod-readersubjects:- kind: ServiceAccount  name: app-sa  namespace: developmentEOF
# List RBAC resourceskubectl get roles,rolebindings -n development
```

Execution

Terminal window

```
kubectl get serviceaccounts,roles,rolebindings -n development
```

Output

Terminal window

```
NAME                     SECRETS   AGEserviceaccount/app-sa    1         2mNAME                 CREATED ATrole.rbac...pod-reader  2m
```

-   verbs define allowed actions (get, list, create, delete)
-   apiGroups depend on resource type (empty = core API)

#### Create ClusterRoles for cluster-wide permissions

Grants cluster-wide permissions across all namespaces

Code

Terminal window

```
# Create cluster rolekubectl apply -f - <<EOFapiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata:  name: node-readerrules:- apiGroups: [""]  resources: ["nodes"]  verbs: ["get", "list", "watch"]- apiGroups: [""]  resources: ["nodes/stats"]  verbs: ["get"]EOF
# Create cluster role bindingkubectl apply -f - <<EOFapiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:  name: node-reader-bindingroleRef:  apiGroup: rbac.authorization.k8s.io  kind: ClusterRole  name: node-readersubjects:- kind: ServiceAccount  name: monitoring-sa  namespace: monitoringEOF
```

Execution

Terminal window

```
kubectl get clusterroles,clusterrolebindings
```

Output

Terminal window

```
NAME                                           CREATED ATclusterrole.rbac.../monitoring-binding     2m
```

-   ClusterRole is cluster-scoped, not namespace-scoped
-   Use for cluster admins and system components

#### Check permissions and debug RBAC

Verifies RBAC permissions and troubleshoots access issues

Code

Terminal window

```
# Check what user can dokubectl auth can-i get pods -n development --as=system:serviceaccount:development:app-sa
# Check multiple permissionskubectl auth can-i create deployments -n defaultkubectl auth can-i delete pods -n default
# List all role bindings for userkubectl get rolebinding,clusterrolebinding -A
# Describe role to see permissionskubectl describe role pod-reader -n development
```

Execution

Terminal window

```
kubectl auth can-i get pods --as=system:serviceaccount:development:app-sa
```

Output

Terminal window

```
yes
```

-   can-i helps verify permissions before assigning access
-   Format: system:serviceaccount:namespace:name

### Network Policies

Control network traffic with network policies

#### Accessibility

Clear examples of network policy configuration

#### Best Practices

-   Start with deny-all policy, then add allowed traffic
-   Use network policies to enforce security boundaries
-   Test policies before production deployment

#### Common Errors

-   **network policy not working:** Verify network plugin supports NetworkPolicy (Calico, Weave)

#### Keywords

networkpolicyingressegressnetworktraffic

[Learn more](https://kubernetes.io/docs/concepts/services-networking/network-policies/)

#### Create network policies for traffic control

Creates network policies to restrict traffic

Code

Terminal window

```
# Create deny-all network policykubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: deny-all  namespace: productionspec:  podSelector: {}  policyTypes:  - Ingress  - EgressEOF
# Create allow policy for specific podskubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: allow-web-traffic  namespace: productionspec:  podSelector:    matchLabels:      app: web  policyTypes:  - Ingress  ingress:  - from:    - podSelector:        matchLabels:          role: frontend    ports:    - protocol: TCP      port: 80EOF
```

Execution

Terminal window

```
kubectl get networkpolicies -n production
```

Output

Terminal window

```
NAME               POD-SELECTOR   AGEdeny-all           <none>         2mallow-web-traffic  app=web        1m
```

-   NetworkPolicy requires network plugin with support
-   podSelector: {} matches all pods

#### Configure egress policies

Restricts outbound traffic from pods

Code

Terminal window

```
# Allow specific egress traffickubectl apply -f - <<EOFapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: allow-egress  namespace: productionspec:  podSelector:    matchLabels:      app: api  policyTypes:  - Egress  egress:  - to:    - podSelector:        matchLabels:          app: database    ports:    - protocol: TCP      port: 5432  - to:    - namespaceSelector:        matchLabels:          name: kube-system    ports:    - protocol: UDP      port: 53EOF
```

Execution

Terminal window

```
kubectl describe networkpolicy allow-egress -n production
```

Output

Terminal window

```
Name:         allow-egressNamespace:    productionEgress:  To: app=database, port: 5432
```

-   Egress allows specifying allowed destination pods
-   DNS access usually required for pod-to-pod communication

### Secrets and Secret Management

Securely store and manage sensitive data

#### Accessibility

Clear examples of secret creation and usage

#### Best Practices

-   Use encrypted storage for secrets at rest
-   Limit secret access with RBAC
-   Rotate secrets regularly

#### Common Errors

-   **secret not found:** Verify secret exists and is in same namespace

#### Keywords

secretsensitivepasswordtokenencryption

[Learn more](https://kubernetes.io/docs/concepts/configuration/secret/)

#### Create and manage secrets

Creates secrets to store sensitive data

Code

Terminal window

```
# Create secret from literalskubectl create secret generic db-secret \  --from-literal=user=admin \  --from-literal=password=secretpass
# Create secret from filekubectl create secret generic app-config \  --from-file=config.yaml
# Create docker registry secretkubectl create secret docker-registry regcred \  --docker-server=myregistry.com \  --docker-username=user \  --docker-password=pass
# List secretskubectl get secrets
```

Execution

Terminal window

```
kubectl get secrets
```

Output

Terminal window

```
NAME         TYPE                  DATA   AGEdb-secret    Opaque                2      2mapp-config   Opaque                1      1m
```

-   Secrets are base64-encoded, not encrypted by default
-   Consider using encryption at rest in production

#### Use secrets in pod specifications

Uses secrets as environment variables in pods

Code

Terminal window

```
# Create pod using secret as environment variableskubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata:  name: app-with-secretspec:  containers:  - name: app    image: myapp    env:    - name: DB_USER      valueFrom:        secretKeyRef:          name: db-secret          key: user    - name: DB_PASSWORD      valueFrom:        secretKeyRef:          name: db-secret          key: password  imagePullSecrets:  - name: regcredEOF
# Verify secret is appliedkubectl describe pod app-with-secret
```

Execution

Terminal window

```
kubectl get pod app-with-secret -o yaml
```

Output

Terminal window

```
env:- name: DB_USER  valueFrom:    secretKeyRef:      name: db-secret      key: user
```

-   imagePullSecrets for private registry authentication
-   Secret data injected at runtime

#### View and update secrets

Views and manages secrets

Code

Terminal window

```
# View decoded secretkubectl get secret db-secret -o jsonpath='{.data.password}' | base64 -d
# Edit secretkubectl edit secret db-secret
# Delete secretkubectl delete secret db-secret
# Get secret as YAMLkubectl get secret db-secret -o yaml
```

Execution

Terminal window

```
kubectl describe secret db-secret
```

Output

Terminal window

```
Name:         db-secretType:         OpaqueDatauser:    5 bytespassword: 10 bytes
```

-   Base64 decoding shows actual values
-   Be careful with secret exposure in logs

## Advanced Operations

Logging, debugging, resource management, and advanced queries

### Logging and Debugging

Collect and analyze logs for troubleshooting

#### Accessibility

Clear examples of logging and debugging workflows

#### Best Practices

-   Check logs first when diagnosing pod issues
-   Use describe to view pod events and conditions
-   Create debug containers instead of modifying production pods

#### Common Errors

-   **not found:** Verify pod you're debugging still exists

#### Keywords

logsdebugtroubleshooteventstracing

[Learn more](https://kubernetes.io/docs/tasks/debug-application-cluster/debug-running-pod/)

#### Advanced logging and filtering

Gets detailed logs with filtering and streaming

Code

Terminal window

```
# Get logs from all containers in podkubectl logs pod-name --all-containers=true
# Get logs from previous pod instancekubectl logs pod-name --previous
# Stream logs with timestampskubectl logs pod-name --timestamps=true -f
# Get logs from specific time rangekubectl logs pod-name --since=1hkubectl logs pod-name --since-time='2025-02-28T10:00:00Z'
# Get logs from multiple podskubectl logs -f -l app=web --max-log-requests=10
# Tail specific number of lineskubectl logs pod-name --tail=100
```

Execution

Terminal window

```
kubectl logs -f pod-name --tail=50
```

Output

Terminal window

```
2025-02-28T10:30:01.123Z INFO Starting application2025-02-28T10:30:02.456Z INFO Connected to database
```

-   \-f flag streams logs in real-time
-   \--previous useful for crashed containers

#### Describe and inspect resources for debugging

Examines resource details and troubleshoots issues

Code

Terminal window

```
# Get full resource detailskubectl describe pod pod-name
# Get resource eventskubectl get events
# Watch resource for changeskubectl get pods --watch
# Get events for specific resourcekubectl get events --field-selector involvedObject.name=pod-name
# Describe deployment to see replica statuskubectl describe deployment web-deployment
# Check resource conditionskubectl get pod pod-name -o jsonpath='{.status.conditions}' | jq .
```

Execution

Terminal window

```
kubectl describe pod pod-name
```

Output

Terminal window

```
Name:         pod-nameStatus:       RunningConditions:  Type    Status  Reason  Ready   True    ContainersReady
```

-   Events show resource state changes
-   Conditions show readiness and health status

#### Advanced debugging with temporary containers

Creates temporary debugging containers

Code

Terminal window

```
# Create debug container in running podkubectl debug pod-name -it --image=busybox
# Debug specific containerkubectl debug pod-name -c container-name -it --image=busybox
# Debug with node accesskubectl debug node/node-name -it --image=ubuntu
# Create copy of pod for debuggingkubectl debug pod-name -it --copy-to=debug-pod
# Share process namespace for debuggingkubectl debug pod-name --target=container-name
```

Execution

Terminal window

```
kubectl debug pod-name -it --image=busybox
```

Output

Terminal window

```
Debugger started, running in pod-name ephemeral-debug-xyz/ #
```

-   Debug containers have tools for troubleshooting
-   Copy-to creates standalone pod for destructive testing

### JSONPath Queries and Output Formatting

Extract specific data with JSONPath queries

#### Accessibility

Clear examples of JSONPath extraction

#### Best Practices

-   Use JSONPath for scripting and automation
-   Custom columns improve readability of output
-   Combine with grep/awk for further filtering

#### Common Errors

-   **unable to parse query:** Check JSONPath syntax and verify field paths exist

#### Keywords

jsonpathqueryextractformattingfilter

[Learn more](https://kubernetes.io/docs/reference/kubectl/jsonpath/)

#### Extract data with JSONPath

Extracts specific fields using JSONPath syntax

Code

Terminal window

```
# Get pod nameskubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Get pod IPskubectl get pods -o jsonpath='{.items[*].status.podIP}'
# Get image names from deploymentkubectl get deployment web -o jsonpath='{.spec.template.spec.containers[*].image}'
# Get container names and imageskubectl get pods -o jsonpath='{.items[*].spec.containers[*].name}'
# Format output with custom columnskubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
```

Execution

Terminal window

```
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
```

Output

Terminal window

```
pod1 pod2 pod3
```

-   jsonpath extracts nested data
-   Can combine with other tools like awk

#### Custom columns and wide output

Creates custom output columns for better readability

Code

Terminal window

```
# Define custom columnskubectl get pods \  -o custom-columns=NAME:.metadata.name,READY:.status.conditions[?(@.type=="Ready")].status,IMAGE:.spec.containers[0].image,IP:.status.podIP
# Format with custom columns shorthandkubectl get pods --sort-by=.metadata.creationTimestamp
# Get pods with sorted outputkubectl get pods --sort-by='{.status.phase}'
# Wide format (standard custom columns)kubectl get pods -o wide
```

Execution

Terminal window

```
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP
```

Output

Terminal window

```
NAME        STATUS    IPpod1        Running   10.244.0.1pod2        Running   10.244.0.2
```

-   Custom columns can format complex nested data
-   Sorting by specific fields helps organize output

#### Complex JSONPath queries with filters

Filters resources based on conditions in JSONPath

Code

Terminal window

```
# Get pods that are currently runningkubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
# Get pods with specific labelkubectl get pods -o jsonpath='{.items[?(@.metadata.labels.tier=="web")].metadata.name}'
# Get containers with specific resource requestskubectl get pods -o jsonpath='{.items[?(@.spec.containers[0].resources.requests.cpu)].metadata.name}'
# Format with line breaks for readabilitykubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\t"}{.status.podIP}{"\n"}{end}'
```

Execution

Terminal window

```
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
```

Output

Terminal window

```
pod1 pod3
```

-   Filter expressions use @.field syntax
-   Complex queries can extract specific information

### Dry-Run and Testing Patterns

Test changes before applying with dry-run

#### Accessibility

Clear examples of dry-run testing

#### Keywords

dry-runtestvalidationpreviewsimulation

#### Preview changes with dry-run

Tests manifest application without creating resources

Code

Terminal window

```
# Preview pod creationkubectl run test-pod --image=nginx --dry-run=client -o yaml
# Preview deployment creationkubectl create deployment web --image=nginx --dry-run=server -o yaml
# Preview manifest applicationkubectl apply -f deployment.yaml --dry-run=client
# Apply with server-side validationkubectl apply -f deployment.yaml --dry-run=server
# Save dry-run output for reviewkubectl apply -f - --dry-run=client -o yaml > deployment-preview.yaml <<EOFapiVersion: apps/v1kind: Deploymentmetadata:  name: webspec:  replicas: 3  selector:    matchLabels:      app: web  template:    metadata:      labels:        app: web    spec:      containers:      - name: nginx        image: nginx:latestEOF
```

Execution

Terminal window

```
kubectl apply -f deployment.yaml --dry-run=client
```

Output

Terminal window

```
deployment.apps/web created (dry run)
```

-   client: validates locally, server: validates on server
-   Useful for checking YAML syntax before applying

#### Validate resources and configurations

Validates manifests before actual deployment

Code

Terminal window

```
# Validate YAML syntaxkubectl apply -f deployment.yaml --dry-run=server
# Check if resource would be createdkubectl create deployment test --image=alpine --dry-run=client
# Validate all manifests in directorykubectl apply -f ./manifests/ --dry-run=server
# Test with specific namespacekubectl apply -f deployment.yaml --namespace=test --dry-run=client
# Get validation detailskubectl apply -f deployment.yaml --dry-run=server -o yaml
```

Execution

Terminal window

```
kubectl apply -f deployment.yaml --dry-run=server -o jsonpath='{.metadata.name}'
```

Output

Terminal window

```
web
```

-   Server-side dry-run catches API errors
-   Good for CI/CD pipeline validation

#### Test resource limits and constraints

Code

Terminal window

```
# Create pod with resource limits to testkubectl apply -f - --dry-run=server <<EOFapiVersion: v1kind: Podmetadata:  name: resource-testspec:  containers:  - name: app    image: myapp    resources:      requests:        cpu: 100m        memory: 128Mi      limits:        cpu: 500m        memory: 512MiEOF
# Check if quota allows creationkubectl apply -f deployment.yaml --dry-run=server --validate=strict
# Test PVC bindingkubectl apply -f pvc.yaml --dry-run=server
```

Execution

Terminal window

```
echo '{"apiVersion":"v1","kind":"Pod","metadata":{"name":"test"},"spec":{"containers":[{"name":"app","image":"nginx"}]}}' | kubectl apply -f - --dry-run=server --validate=strict
```

Was this useful?

## Tags

#Kubernetes#Kubectl#Containers#Orchestration#Cloud Native#K8s#Container Orchestration#Cluster Management

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Kubernetes&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes&title=Kubernetes&summary=Kubernetes%20is%20an%20open-source%20container%20orchestration%20platform%20for%20automating%20deployment%2C%20scaling%2C%20and%20management%20of%20containerized%20applications.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Kubernetes%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes&text=Kubernetes "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes&title=Kubernetes "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes&t=Kubernetes "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes&media=&description=Kubernetes%20is%20an%20open-source%20container%20orchestration%20platform%20for%20automating%20deployment%2C%20scaling%2C%20and%20management%20of%20containerized%20applications. "Share on Pinterest")[Email](<mailto:?subject=Kubernetes&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubernetes>)

## Comments

## You might also enjoy

More posts on similar topics

## [kubectl](/cheatsheets/kubectl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   CLI
-   Container Orchestration
-   Cloud Native

kubectl is the command-line tool you use to talk to a Kubernetes cluster. Whatever you can do through a dashboard, you can do faster here: deploy apps, inspect resources, stream logs, run commands ins

#Kubectl#Kubernetes#K8s+5 tags

[read more](/cheatsheets/kubectl)

## [Helm](/cheatsheets/helm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   Helm
-   Package Management
-   Cloud Native

Helm is the package manager for Kubernetes that simplifies the deployment, management, and upgrade of applications. It uses charts, which are templated Kubernetes manifests, to build reusable, configu

#Helm#Kubernetes#Package Manager+5 tags

[read more](/cheatsheets/helm)

## [Docker](/cheatsheets/docker)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Deployment

Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run applicati

#Docker#Containers#Images+3 tags

[read more](/cheatsheets/docker)

## [Docker Swarm](/cheatsheets/docker-swarm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Orchestration
-   Deployment

This cheatsheet is a reference for managing Docker Swarm clusters, services, and stacks. It covers the commands and best practices for scaling, updating, and monitoring your swarm applications.

#Docker Swarm#Orchestration#Containers+4 tags

[read more](/cheatsheets/docker-swarm)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

6 related posts
