Deploying Web Applications on Kubernetes: A Beginner's Guide

Beginner's guide to deploying web applications on Kubernetes. Learn the basics, step-by-step instructions, and best practices for successful deployments
E
Edtoks12:23 min read

Introduction to Kubernetes

What is Kubernetes?

Kubernetes is an open-source container orchestration platform designed to automate the deployment, scaling, and operation of application containers. It groups containers that make up an application into logical units for easy management and discovery.

Key Concepts

  • Pod: The smallest and simplest Kubernetes object. A Pod represents a single instance of a running process in your cluster.

  • Node: A worker machine in Kubernetes, which may be a VM or a physical machine.

  • Cluster: A set of Nodes that run containerized applications.

  • Deployment: A higher-level concept that manages replica sets to keep your application running.

  • Service: An abstraction that defines a logical set of Pods and a policy by which to access them.

Advantages of Kubernetes

  • Scalability: Automatically scale your applications up and down based on load.

  • Self-Healing: Automatically restarts failed containers and reschedules terminated containers.

  • Rolling Updates: Deploy new versions of your application without downtime.

  • Service Discovery and Load Balancing: Automatically assign IP addresses and a single DNS name for your application.

  • Storage Orchestration: Automatically mount the storage system of your choice.

Key Steps: Building to Deployment to Management

Step 1: Generate and Push the Container Image

First, create a Dockerfile for your web application.

Dockerfile Example:

# Use an official Node.js runtime as a parent image
FROM node:14

# Set the working directory
WORKDIR /usr/src/app

# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy the rest of the application code
COPY . .

# Expose the application port
EXPOSE 8080

# Run the application
CMD ["node", "app.js"]

Build the Docker image and push it to a container registry (e.g., Docker Hub).

# Build the Docker image
docker build -t <your-dockerhub-username>/webapp:latest .

# Push the Docker image
docker push <your-dockerhub-username>/webapp:latest

Step 2: Configurations Using ConfigMaps and Secrets

What is a ConfigMap?

A ConfigMap is a Kubernetes object that allows you to store configuration data as key-value pairs. This configuration data can be used by your applications to customize their behavior without the need to hard-code values in your application code. ConfigMaps are particularly useful for storing non-sensitive data such as configuration settings, URLs, and environment-specific variables.

ConfigMap Example:

Create a file named configmap.yaml.

apiVersion: v1
kind: ConfigMap
metadata:
  name: webapp-config
data:
  APP_ENV: "production"
  APP_DEBUG: "false"

Explanation of Parameters:

  • apiVersion: Specifies the API version of the resource. For ConfigMap, it is v1.

  • kind: Specifies the type of Kubernetes resource, which is ConfigMap.

  • metadata: Contains metadata about the resource, such as name.

    • name: The name of the ConfigMap (webapp-config).

  • data: Holds the key-value pairs that represent the configuration data.

    • APP_ENV: An environment variable set to production.

    • APP_DEBUG: An environment variable set to false.

Apply the ConfigMap.

kubectl apply -f configmap.yaml

What is a Secret?

A Secret is a Kubernetes object that stores sensitive information, such as passwords, OAuth tokens, and SSH keys, in a secure manner. Secrets are similar to ConfigMaps but are specifically designed for sensitive data. They can be referenced in your Pods to provide sensitive data without exposing it directly in your configuration files.

Secret Example:

Create a file named secret.yaml.

apiVersion: v1
kind: Secret
metadata:
  name: webapp-secret
type: Opaque
data:
  DATABASE_PASSWORD: c2VjcmV0cGFzc3dvcmQ=  # base64 encoded value of "secretpassword"

Explanation of Parameters:

  • apiVersion: Specifies the API version of the resource. For Secret, it is v1.

  • kind: Specifies the type of Kubernetes resource, which is Secret.

  • metadata: Contains metadata about the resource, such as name.

    • name: The name of the Secret (webapp-secret).

  • type: Specifies the type of Secret. Opaque is the default type.

  • data: Holds the key-value pairs that represent the sensitive data, which must be base64 encoded.

    • DATABASE_PASSWORD: The base64 encoded value of secretpassword.

Apply the Secret.

kubectl apply -f secret.yaml

Step 3: Deploying the Application Using Deployment

What is a Deployment?

A Deployment in Kubernetes is a higher-level object that manages the deployment of replica sets and ensures that a specified number of Pods are running at all times. Deployments provide declarative updates to applications, making it easier to roll out changes, roll back to previous versions, and scale the number of replica Pods up or down.

Deployment Example:

Create a file named deployment.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: <your-dockerhub-username>/webapp:latest
        ports:
        - containerPort: 8080
        env:
        - name: APP_ENV
          valueFrom:
            configMapKeyRef:
              name: webapp-config
              key: APP_ENV
        - name: DATABASE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: webapp-secret
              key: DATABASE_PASSWORD

Explanation of Parameters:

  • apiVersion: Specifies the API version of the resource. For Deployment, it is apps/v1.

  • kind: Specifies the type of Kubernetes resource, which is Deployment.

  • metadata: Contains metadata about the resource, such as name.

    • name: The name of the Deployment (webapp-deployment).

  • spec: Defines the desired state of the Deployment.

    • replicas: The number of Pod replicas to run (3).

    • selector: Defines how to identify the Pods managed by this Deployment.

      • matchLabels: Labels used to identify the Pods (app: webapp).

    • template: Specifies the Pod template used by the Deployment.

      • metadata: Metadata for the Pods.

        • labels: Labels to apply to the Pods (app: webapp).

      • spec: Specifies the container configuration for the Pods.

        • containers: Defines the containers within the Pod.

          • name: The name of the container (webapp).

          • image: The container image to use (<your-dockerhub-username>/webapp:latest).

          • ports: The ports to expose from the container.

            • containerPort: The port the container listens on (8080).

          • env: Environment variables to set in the container.

            • name: The name of the environment variable (APP_ENV).

              • valueFrom: Specifies the source of the value.

                • configMapKeyRef: Refers to a key in a ConfigMap.

                  • name: The name of the ConfigMap (webapp-config).

                  • key: The key in the ConfigMap (APP_ENV).

            • name: The name of the environment variable (DATABASE_PASSWORD).

              • valueFrom: Specifies the source of the value.

                • secretKeyRef: Refers to a key in a Secret.

                  • name: The name of the Secret (webapp-secret).

                  • key: The key in the Secret (DATABASE_PASSWORD).

Apply the Deployment.

kubectl apply -f deployment.yaml

Step 4: Expose the Application Using the Service

What is a Service?

A Service in Kubernetes is an abstraction that defines a logical set of Pods and a policy by which to access them. Services enable communication between different components of your application and can expose your application to external traffic. Kubernetes supports various types of Services, including ClusterIP, NodePort, and LoadBalancer, each serving different use cases.

Service Example:

Create a file named service.yaml.

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

Explanation of Parameters:

  • apiVersion: Specifies the API version of the resource. For Service, it is v1.

  • kind: Specifies the type of Kubernetes resource, which is Service.

  • metadata: Contains metadata about the resource, such as name.

    • name:

The name of the Service (webapp-service).

  • spec: Defines the desired state of the Service.

    • selector: Specifies which Pods the Service should target.

      • app: The label used to select the Pods (webapp).

    • ports: Specifies the ports to expose from the Service.

      • protocol: The protocol used by the port (TCP).

      • port: The port exposed by the Service (80).

      • targetPort: The port the container listens on (8080).

    • type: Specifies the type of Service. LoadBalancer creates an external load balancer.

Apply the Service.

kubectl apply -f service.yaml

Step 5: Managing the Deployment Strategy

What are Deployment Strategies?

Deployment strategies define how updates to applications are rolled out. The most common strategy is rolling updates, where updates are applied incrementally to minimize downtime and ensure the application remains available during the update process. Other strategies include recreate, which stops all old Pods before starting new ones.

Rolling Updates Example:

By default, Kubernetes Deployment uses rolling updates for new versions. To specify the strategy explicitly, include it in the Deployment manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: <your-dockerhub-username>/webapp:latest
        ports:
        - containerPort: 8080

Explanation of Parameters:

  • strategy: Defines the strategy for deploying updates.

    • type: Specifies the type of deployment strategy. RollingUpdate is the default.

    • rollingUpdate: Configures parameters for rolling updates.

      • maxUnavailable: The maximum number of Pods that can be unavailable during the update process (1).

      • maxSurge: The maximum number of Pods that can be created above the desired number of replicas during the update (1).

Apply the Deployment with the strategy.

kubectl apply -f deployment.yaml

Conclusion

By following these steps, you can successfully deploy a web application on Kubernetes. You started by generating and pushing a container image, configured the application using ConfigMaps and Secrets, deployed it using a Deployment, and exposed it using a Service. Finally, you learned how to manage the deployment strategy and understood the main parameters in Kubernetes manifest files.

Kubernetes provides a robust and flexible platform for deploying, scaling, and managing containerized applications. With the knowledge from this guide, you're well on your way to leveraging Kubernetes for your web applications.

Additional Topics

  • Health Checks: Use liveness and readiness probes to ensure your application is running correctly.

  • Auto-Scaling: Configure Horizontal Pod Autoscalers (HPA) to automatically scale your applications based on load.

  • Monitoring and Logging: Integrate with tools like Prometheus, Grafana, and ELK stack for monitoring and logging.

  • RBAC: Implement Role-Based Access Control (RBAC) to manage permissions and access within your Kubernetes cluster.

This comprehensive guide should help your readers understand the process of deploying web applications on Kubernetes, from the basics to advanced topics. Feel free to add any additional details or examples as needed!

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.