Kubernetes Pod Deployment

In this guide, we will write a bash script to automate the deployment of Kubernetes pods. The script will include detailed steps and practical examples to make the automation process straightforward and efficient. This script can serve as a foundation for automating more complex Kubernetes deployments.


Overview

This script will:

  1. Verify prerequisites (kubectl and kubeconfig).
  2. Define and deploy Kubernetes pods using a YAML configuration file.
  3. Check the status of the deployed pods.
  4. Handle cleanup (delete pods or deployments if necessary).

Prerequisites

Before we begin:

  1. Install Kubernetes CLI (kubectl): Ensure kubectl is installed and configured. Use the command:
    kubectl version --client
    
  2. Kubeconfig File: Ensure your kubeconfig file is properly set up to access the Kubernetes cluster.
  3. YAML File for Pod Deployment: Have a deployment YAML file ready.

Kubernetes Pod

A Kubernetes Pod is the smallest and simplest deployable unit in Kubernetes. It represents a single instance of a running process in a cluster. Pods encapsulate one or more containers (usually Docker containers) that share the same network namespace, storage, and configuration.

1. Encapsulation of Containers

  • A Pod can run one or more containers, which are tightly coupled and share resources.
  • Commonly, a Pod runs a single container. In cases where multiple containers are needed (e.g., a sidecar container), they are grouped within the same Pod.

2. Shared Resources

  • Network: All containers in a Pod share the same IP address and port namespace. This means they can communicate with each other using localhost and avoid using inter-container networking.
  • Storage: Containers in a Pod can share persistent storage volumes.

3. Ephemeral Nature

  • Pods are designed to be short-lived. If a Pod fails, Kubernetes replaces it with a new instance (if managed by a higher-level abstraction like a Deployment or ReplicaSet).

4. Lifecycle Management

  • Pods have defined lifecycle phases: Pending, Running, Succeeded, Failed, and Unknown.
  • Kubernetes ensures the desired state of Pods, but Pods themselves are not resilient. For self-healing and scaling, higher-level controllers (e.g., Deployments) manage Pods.

5. Labels and Selectors

  • Pods are assigned labels, which can be used to identify and manage them using selectors.

Script

Below is the complete bash script with explanations for each step.

#!/bin/bash

# Automating Kubernetes Pod Deployment
# Author: [Your Name]
# Date: [Date]
# Version: 1.0

# Icons for status display
CHECK="\u2714" # ✔
CROSS="\u274C" # ✘
INFO="\u2139"  # ℹ

# Function: Check if a command exists
function check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "${CROSS} Error: $1 is not installed or available in the PATH."
        exit 1
    else
        echo -e "${CHECK} $1 is installed."
    fi
}

# Function: Check kubectl access
function check_kubectl_access() {
    if ! kubectl cluster-info > /dev/null 2>&1; then
        echo -e "${CROSS} Error: Unable to connect to the Kubernetes cluster. Please check kubeconfig."
        exit 1
    else
        echo -e "${CHECK} Connected to Kubernetes cluster."
    fi
}

# Function: Deploy the YAML file
function deploy_yaml() {
    local yaml_file=$1
    if [[ -f $yaml_file ]]; then
        echo -e "${INFO} Applying deployment file: $yaml_file"
        kubectl apply -f "$yaml_file"
    else
        echo -e "${CROSS} Error: YAML file $yaml_file not found."
        exit 1
    fi
}

# Function: Check the status of pods
function check_pods_status() {
    local app_label=$1
    echo -e "${INFO} Checking the status of pods for app label: $app_label"
    kubectl get pods -l app="$app_label" --watch --timeout=60s
}

# Function: Clean up deployment
function cleanup_deployment() {
    local app_label=$1
    echo -e "${INFO} Deleting resources with app label: $app_label"
    kubectl delete all -l app="$app_label"
}

# Main script starts here
echo "=== Kubernetes Deployment Automation Script ==="

# Step 1: Check prerequisites
check_command kubectl
check_kubectl_access

# Step 2: YAML file for deployment
read -p "Enter the path to your deployment YAML file (default: deployment.yaml): " yaml_file
yaml_file=${yaml_file:-deployment.yaml}

# Step 3: App label for the deployment
read -p "Enter the app label for the deployment (e.g., myapp): " app_label
if [[ -z $app_label ]]; then
    echo -e "${CROSS} Error: App label cannot be empty."
    exit 1
fi

# Step 4: Deploy the YAML file
deploy_yaml "$yaml_file"

# Step 5: Check the status of the pods
check_pods_status "$app_label"

# Step 6: Optional Cleanup
read -p "Do you want to clean up the deployment? (yes/no): " cleanup
if [[ $cleanup == "yes" ]]; then
    cleanup_deployment "$app_label"
    echo -e "${CHECK} Deployment cleaned up successfully."
else
    echo -e "${INFO} Deployment retained."
fi

echo -e "${CHECK} Script execution completed."

Kubernetes Pod Deployment Step-by-Step Explanation

1. Checking Prerequisites

The script ensures that kubectl is installed and accessible. This is done with the command -v check:

check_command kubectl

If kubectl is not found, the script terminates with an error.

2. Verifying Kubernetes Cluster Access

The script checks if the user can connect to the Kubernetes cluster using kubectl cluster-info:

check_kubectl_access

This ensures the kubeconfig is valid and the cluster is reachable.

3. Defining the Deployment YAML

The user provides the path to a YAML file, which contains the configuration for the Kubernetes pod or deployment. A default file name (deployment.yaml) is used if none is provided:

read -p "Enter the path to your deployment YAML file (default: deployment.yaml): " yaml_file
yaml_file=${yaml_file:-deployment.yaml}

4. App Label for Deployment

The app label is a critical identifier for the pods, services, or deployments. It is used to:

  • Deploy resources.
  • Check the status of the pods.
  • Perform cleanup operations.

The script prompts the user for an app label:

read -p "Enter the app label for the deployment (e.g., myapp): " app_label

5. Applying the YAML File

The script applies the provided YAML configuration to create or update resources in Kubernetes:

kubectl apply -f "$yaml_file"

If the file is missing, the script exits with an error.

6. Monitoring Pod Status

The kubectl get pods command watches the pods associated with the given app label:

kubectl get pods -l app="$app_label" --watch --timeout=60s

This provides real-time updates on the pod status for 60 seconds.

7. Cleanup (Optional)

The user has the option to delete all resources (pods, services, deployments, etc.) associated with the app label:

kubectl delete all -l app="$app_label"

This ensures the environment can be reset after testing.


Example YAML File

Save the following YAML configuration as deployment.yaml. This example creates a deployment with a single Nginx pod:

https://linuxcloudservers.com/wp-content/uploads/2025/01/pod.pngapiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: myapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

Script Execution Example

  1. Run the Script:
    ./k8s_deploy.sh
    
  2. Provide Inputs:
    • Path to YAML file: deployment.yaml
    • App label: myapp
  3. Output:
    === Kubernetes Deployment Automation Script ===
    ✔ kubectl is installed.
    ✔ Connected to Kubernetes cluster.
    ℹ Applying deployment file: deployment.yaml
    ℹ Checking the status of pods for app label: myapp
    NAME                                READY   STATUS    RESTARTS   AGE
    nginx-deployment-7bb8dc99f5-lt6zq   1/1     Running   0          10s
    Do you want to clean up the deployment? (yes/no): yes
    ℹ Deleting resources with app label: myapp
    ✔ Deployment cleaned up successfully.
    ✔ Script execution completed.
    

difference between pod and deployment in kubernetes​

In Kubernetes, Pods and Deployments are closely related but serve different purposes. Here’s a detailed comparison to clarify the difference between the two:


1. Pod

A Pod is the smallest deployable unit in Kubernetes and represents one or more containers that are tightly coupled.

Key Features:

  • Single Unit of Deployment: A pod can host one or more containers that share the same network namespace and storage volumes.
  • Ephemeral by Nature: Pods are transient; if a pod fails, Kubernetes does not automatically recreate it (unless managed by a controller like a Deployment).
  • Networking: All containers in a pod share the same IP address and port space, enabling them to communicate via localhost.
  • Use Cases:
    • Running a simple or one-time task.
    • Directly deploying a specific set of tightly coupled containers.

Example YAML:

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
    - name: nginx
      image: nginx:latest

2. Deployment

A Deployment is a Kubernetes controller that manages the lifecycle of pods, ensuring high availability and scalability.

Key Features:

  • Manages Pods: Deployments create and maintain ReplicaSets, which manage the desired number of pod replicas.
  • Self-Healing: If a pod managed by a Deployment fails, the Deployment automatically recreates it.
  • Scaling: You can scale the number of replicas up or down dynamically.
  • Rolling Updates: Supports rolling updates and rollbacks to ensure zero downtime during upgrades.
  • Use Cases:
    • Deploying stateless applications.
    • Managing applications that require scalability and high availability.
    • Performing updates or rollbacks seamlessly.

Example YAML:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:latest

Comparison Table

Feature Pod Deployment
Definition Smallest deployable unit in Kubernetes. Manages pods and their replicas.
Purpose Runs one or more tightly coupled containers. Ensures high availability and scalability.
Resilience Not resilient; fails if the pod crashes. Automatically recreates failed pods.
Scaling Manual; requires creating multiple pods manually. Automatic; manages replicas via ReplicaSets.
Updates Requires manual replacement. Supports rolling updates and rollbacks.
Use Case Small, one-off tasks or testing. Production-grade applications requiring high availability.

When to Use:

  • Pods:
    • For debugging or testing purposes.
    • For one-off jobs or small tasks that don’t need scaling or high availability.
  • Deployments:
    • For production environments where uptime, scaling, and resilience are critical.
    • For applications that need versioned updates and rollbacks.

By understanding these differences, you can determine the appropriate resource to use based on your application’s requirements!

Icons in Action

  • ✔ (Check): Indicates successful steps.
  • ✘ (Cross): Displays errors.
  • ℹ (Info): Provides status updates.

Benefits of Automation

  1. Consistency: Avoid manual errors by standardizing the deployment process.
  2. Efficiency: Save time by automating repetitive tasks.
  3. Scalability: Extend the script to support multiple deployments or clusters.
  4. Integration: Combine with CI/CD pipelines for continuous delivery.

Reference