Launch Kubernetes pods and expose them using Jenkins

Launch Kubernetes pods and expose them using Jenkins

To launch Kubernetes pods and expose them using Jenkins, you'll need to create a Jenkins job that interacts with your Kubernetes cluster. This guide will outline the steps to set up a Jenkins pipeline that deploys a Kubernetes application (like an Nginx server) and exposes it through a service.

Prerequisites

  1. Jenkins Installed: Make sure you have Jenkins installed and running.

  2. Kubernetes Cluster: Ensure you have access to a Kubernetes cluster where you can deploy pods.

  3. Kubeconfig: You should have the kubeconfig file configured on the Jenkins server to communicate with the Kubernetes cluster.

  4. Jenkins Kubernetes Plugin: Install the Kubernetes CLI plugin in Jenkins if you haven't done so already.

Step-by-Step Guide

Step 1: Create a New Pipeline Job

  1. Open your Jenkins dashboard.

  2. Click on "New Item".

  3. Enter a name for your job (e.g., Deploy to Kubernetes).

  4. Select "Pipeline" and click OK.

Step 2: Configure the Pipeline Job

  1. In the job configuration page, scroll down to the "Pipeline" section.

  2. Choose "Pipeline script" from the dropdown.

Step 3: Add the Pipeline Script

In the "Pipeline" script text area, add the following script:

pipeline {
    agent any

    stages {
        stage('Clone Repository') {
            steps {
                // Clone your application repository
                git url: 'https://github.com/yourusername/your-app-repo.git'
            }
        }

        stage('Build and Push Docker Image') {
            steps {
                script {
                    // Build Docker image
                    sh 'docker build -t your-docker-repo/your-app:${env.BUILD_ID} .'

                    // Log in to Docker Hub (or your registry)
                    sh 'echo "${DOCKER_PASSWORD}" | docker login -u "${DOCKER_USERNAME}" --password-stdin'

                    // Push Docker image
                    sh 'docker push your-docker-repo/your-app:${env.BUILD_ID}'
                }
            }
        }

        stage('Deploy to Kubernetes') {
            steps {
                script {
                    // Set the namespace (optional)
                    def namespace = 'default'

                    // Create a Kubernetes deployment
                    sh """
                    kubectl apply -f - <<EOF
                    apiVersion: apps/v1
                    kind: Deployment
                    metadata:
                      name: your-app
                      namespace: ${namespace}
                    spec:
                      replicas: 3
                      selector:
                        matchLabels:
                          app: your-app
                      template:
                        metadata:
                          labels:
                            app: your-app
                        spec:
                          containers:
                          - name: your-app
                            image: your-docker-repo/your-app:${env.BUILD_ID}
                            ports:
                            - containerPort: 80
                    EOF
                    """

                    // Expose the deployment as a service
                    sh """
                    kubectl expose deployment your-app --type=LoadBalancer --name=your-app-service --port=80 --target-port=80 --namespace=${namespace}
                    """
                }
            }
        }
    }

    environment {
        DOCKER_USERNAME = credentials('docker-username')  // Jenkins credentials ID for Docker username
        DOCKER_PASSWORD = credentials('docker-password')  // Jenkins credentials ID for Docker password
    }
}

Explanation of the Pipeline Script

  1. Clone Repository: The first stage clones your application repository from GitHub or another source control system.

  2. Build and Push Docker Image:

    • The script builds a Docker image using the Dockerfile in the repository.

    • It logs in to Docker Hub (or your specified registry) using credentials stored in Jenkins.

    • Finally, it pushes the Docker image to the specified repository.

  3. Deploy to Kubernetes:

    • It applies a Kubernetes deployment configuration to create pods running your application.

    • The deployment specifies 3 replicas of the application, exposing port 80.

    • The deployment is then exposed as a LoadBalancer service to make it accessible.

Step 4: Save and Run the Job

  1. Click "Save" at the bottom of the job configuration page.

  2. Go back to the job's main page and click "Build Now" to execute the job.

Step 5: Verify the Deployment

  1. After the job completes successfully, you can verify the deployment by running:

     kubectl get pods
     kubectl get services
    
  2. You should see your application pods running and the service exposed. Depending on your Kubernetes setup, you may be able to access the service via the external IP address of the LoadBalancer.

Additional Considerations

  • Jenkins Permissions: Ensure that the Jenkins user has the necessary permissions to run kubectl commands on your Kubernetes cluster.

  • Error Handling: Consider adding error handling in your script to manage deployment failures.

  • Environment Variables: You can use Jenkins environment variables to manage configurations and secrets.

Conclusion

By following these steps, you have successfully created a Jenkins pipeline that deploys Kubernetes pods and exposes them via a service. This setup can be adapted for more complex applications and environments.