Hands-On Guide: Creating and Managing Kubernetes Pods and Services

Introduction

Kubernetes Pods and Services are fundamental components for managing containerized applications. Pods encapsulate one or more containers and form the basic unit of deployment. They facilitate the co-location of tightly coupled application components. Services, on the other hand, provide network access to pods, enabling seamless communication within the cluster and exposing applications externally. In this guide, we'll explore the concepts of Pods and Services, learn how to create and manage them, and understand their crucial roles in orchestrating scalable and resilient containerized applications. Whether you're new to Kubernetes or seeking deeper insights, this guide will help you navigate these core Kubernetes constructs effectively.

Pod:

  • A Pod is the smallest deployable unit in Kubernetes.

  • In K8S, every container will be created inside POD only.

  • Pods always run on a Node in the cluster.

  • Each Pod represents a single running process.

  • Pods can contain one or more containers that share network and storage namespaces.

  • Multiple Pods can run on a single Node.

  • Every Pod has a unique IP address.

Your statement correctly identifies two primary approaches for creating Pods in Kubernetes:

  1. Interactive Approach:

    • In the interactive approach, you use the kubectl run command to create a Pod interactively from the command line.

    • Here's the basic syntax for creating a Pod interactively:

        kubectl run --name <pod-name> --image=<image-name>
        // Example
        kubectl run --name my-pod --image nginx
      
    • This command creates a Pod with the specified name and runs a container with the specified image.

  2. Declarative Approach (Kubernetes Manifest YAML):

    • In the declarative approach, you define the desired state of the Pod using a YAML manifest file and then apply that manifest to the Kubernetes cluster.

    • You write a YAML file that specifies the Pod's configuration, including details like the container image, ports, and labels.

    • Here's a simplified example of a Pod manifest in YAML:

        apiVersion: v1
        kind: Pod
        metadata:
          name: my-pod
        spec:
          containers:
          - name: my-container
            image: my-image
      
    • You then apply the manifest using the kubectl apply command:

        kubectl apply -f pod-manifest.yaml
      
    • Kubernetes will create the Pod according to the specifications defined in the manifest file.

YAML File :

YAML (short for "YAML Ain't Markup Language" or sometimes "Yet Another Markup Language") is a human-readable data serialization format. It's often used for configuration files and data exchange between languages with different data structures. YAML uses indentation to represent the structure of data, making it easy for both humans and machines to read and write.

YAML Syntax:

  1. Indentation: YAML uses indentation to represent the hierarchy of data. Use spaces (typically 2 or 4) for indentation, but be consistent throughout your file.

  2. Comments: Lines starting with # are treated as comments and are ignored by parsers.

  3. Key-Value Pairs: Key-value pairs are written with a colon (:) separating the key and value. Keys are typically strings, and values can be strings, numbers, booleans, arrays, dictionaries, or null.

  4. Lists/Arrays: Lists or arrays are represented using a hyphen (-) followed by a space, and each item is indented one level.

  5. Dictionaries/Maps: Dictionaries or maps are defined using key-value pairs, where keys are followed by colons (:), and values are indented one level.

Example for an Array in YAML:

    fruits:
      - apple
      - banana
      - orange

In this example, we have a dictionary with a key "fruits," and its value is an array of three fruits.

Example for a Dictionary in YAML:

    person:
      name: John Doe
      age: 30
      address:
        street: 123 Main St
        city: Exampleville
        zip: '12345'

In this example, we have a dictionary named "person" with keys "name," "age," and "address." The "address" key has a nested dictionary with its own keys.

Remember that YAML is sensitive to indentation, so ensure that you maintain consistent spacing. Additionally, strings can be written with or without quotes, but if a string contains special characters, it's a good practice to use quotes to avoid any ambiguity.

YAML is widely used in various programming languages and configuration files for its readability and simplicity.

Kubernetes Manifest YAML:

  • Kubernetes uses YAML files to define the desired state of resources.

  • These YAML files specify the API version, kind, metadata, and the desired specifications for the resource.

  1.   apiVersion:
      kind:
      metadata:
      spec:
    

Sure, here's an example of a Kubernetes POD manifest YAML file along with some common commands for managing and interacting with the POD:

Kubernetes POD Manifest YAML:

---
apiVersion: v1
kind: Pod
metadata:
  name: javawebapppod
  labels:
    app: javawebapp
spec:
  containers:
  - name: javawebappcontainer
    image: pankaj1998/maven-web-app
    ports:
    - containerPort: 8080

Common Kubernetes POD Commands:

  1. Display all pods that are created:

     $ kubectl get pods
    

    This command lists all the pods running in the current namespace.

  2. Create PODs using the pod-manifest YAML file:

     $ kubectl apply -f <pod-yml>
     // save above file as pod-java.yml
     $ kubectl apply -f pod-java.yml
    

    Replace <pod-yml> with the filename of your YAML manifest. This command deploys the pod described in the YAML file.

  3. Describe a pod to get more information about it:

     $ kubectl describe pod <pod-name>
    

    Replace <pod-name> with the name of the pod you want to describe. This command provides detailed information about the specified pod, including its events, containers, and more.

  4. Get pod logs:

     $ kubectl logs <pod-name>
    

    Replace <pod-name> with the name of the pod you want to retrieve logs from. This command fetches the logs from the specified pod's containers.

  5. Get the worker node on which a pod is running:

     $ kubectl get pods -o wide
    

    This command lists all the pods along with additional information, including the node on which each pod is running.

These commands are useful for managing and troubleshooting pods in a Kubernetes cluster. Remember to replace <pod-yml> and <pod-name> with your actual YAML file and pod name when executing these commands.

Kubernetes Service:

  • Kubernetes Services are used to expose Pods to the outside world.

  • There are three types of Services:

    1. Cluster IP

    2. NodePort

    3. LoadBalancer

  • Services are defined in YAML files and associated with Pods using labels.

  • Cluster IP services expose Pods internally within the cluster.

  • NodePort services expose Pods on a specific port on all Nodes.

  • LoadBalancer services provision an external load balancer for Pods.

Certainly! Here's an explanation of each of the three types of Kubernetes services.

  1. Cluster IP Service:

    • Purpose: Cluster IP services provide a stable, internal IP address within the Kubernetes cluster. They are used to expose pods to other pods or services within the same cluster.

    • Accessibility: Cluster IP services are accessible only from within the cluster. They are not reachable from outside the cluster.

    • Use Case: They are commonly used for internal communication between different components or microservices within the cluster.

    • Example: If you have a web application with multiple microservices, you might use a Cluster IP service to allow those microservices to communicate with each other.

Kubernetes ClusterIP Service Manifest YAML:

    ---
    apiVersion: v1
    kind: Service
    metadata:
     name: javawebappsvc
    spec:
      type: ClusterIP
      selector:
        app: javawebapp # POD lable
      ports:
      - port: 80
        targetPort: 8080
    ...
  1. Node Port Service:

    • Purpose: Node Port services provide a way to expose a pod to the outside world, typically on a specific port of each node in the cluster.

    • Accessibility: They are accessible from outside the cluster using the node's IP address and a specific port number.

    • Use Case: Node Port services are useful when you need to expose a service to external clients or users, but you don't want to set up a Load Balancer.

    • Example: You might use a Node Port service to expose a web application to external users by forwarding traffic to a specific port on the nodes.

      Kubernetes Node Port Service Manifest YAML:

        apiVersion: v1
        kind: Service
        metadata:
          name: javawebappsvc
        spec:
          type: NodePort
          selector:
            app: javawebapp  #POD label
          ports:
            - port: 80
              targetPort: 8080
              nodePort: 30785
      
  2. Load Balancer Service:

    • Purpose: Load Balancer services provide a way to expose a pod or a group of pods to the outside world with load balancing capabilities. They typically work with cloud providers to provision external load balancers.

    • Accessibility: Load Balancer services are accessible from outside the cluster, and they distribute incoming traffic across multiple pods for high availability.

    • Use Case: They are suitable for applications that require external access and need load balancing for distributing traffic across multiple replicas.

    • Example: If you have a web application that needs to handle a high volume of external traffic, you might use a Load Balancer service to distribute that traffic across multiple pods for better performance and redundancy.

      Kubernetes ClusterIP Service Manifest YAML:

        ---
        apiVersion: v1
        kind: Service
        metadata:
          name: javawebappsvc
        spec:
          type: LoadBalancer
          selector:
            app: javawebapp  #POD label
          ports:
            - port: 80
              targetPort: 8080
        ...
      

Combined Manifest:

  • You can define both a Pod and a Service in a single YAML file.

  • This simplifies deployment and ensures that the Service is associated with the correct Pods.

Combined Kubernetes Manifest YAML:

---
apiVersion: v1
kind: Pod
metadata:
  name: javawebapppod
  labels:
    app: javawebapp # Very important label
spec:
  containers:
  - name: javaweappcontainer
    image: pankaj1998/maven-web-app
    ports:
      - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: javawebappsvc
spec:
  type: NodePort
  selector:
    app: javawebapp  # POD label
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30785

Commands for Managing the Kubernetes Resources:

  1. Delete All Kubernetes Components You Have Created:

     $ kubectl delete all --all
    

    This command will delete all pods, services, and other resources in your current namespace.

  2. Apply the Manifest:

     $ kubectl apply -f <manifest-yml>
    

    Replace <manifest-yml> with the filename of your combined YAML manifest. This command will create both the pod and the service defined in the manifest.

  3. Get Pods:

     $ kubectl get pods
    

    After applying the manifest, you can use this command to list all the pods in your current namespace. It should include the "javawebapppod" pod.

  4. Get Service:

     $ kubectl get svc
    

    Running this command will list all the services in your current namespace, including the "javawebappsvc" service that you created.

  5. Check Which Node the Pod Is Running On:

     $ kubectl get pods -o wide
    

    This command provides detailed information about the pods, including the node on which each pod is running. Use it to find out which node is hosting the "javawebapppod" pod.

Pod Lifecycle:

  • Pods have a lifecycle from creation to deletion.

  • Requests to create Pods are processed by the Kubernetes control plane.

  • The Scheduler schedules Pods to run on specific worker nodes.

  • The kubelet on each node starts the container(s) in the Pod.

  • Pods are considered ephemeral and can be recreated if necessary.

Overall, your explanation covers the basics of deploying and managing Pods in Kubernetes, which is crucial for anyone getting started with container orchestration in Kubernetes.