CLOUDLAUNCH/LAB

Chapter 12 · EC2-only Kubernetes lab

Deploy a containerized Flask app with Jenkins

Follow this ordered EC2 lab: run Jenkins, install plugins, configure credentials, prepare Kubernetes, connect the GitHub repository, build the image, deploy manifests, create the Jenkinsfile, and expose the application.

Lab order

  1. 1. Run Jenkins on EC2
  2. 2. Install Docker and Kubernetes plugins
  3. 3. Add Docker Hub and kubeconfig credentials
  4. 4. Prepare the EC2 Kubernetes cluster
  5. 5. Fork or clone Nerd503/python-flask-pipeline
  6. 6. Check out the Flask application
  7. 7. Create the Dockerfile
  8. 8. Create Deployment and Service YAML
  9. 9. Add and modify the Jenkinsfile
  10. 10. Push changes to GitHub
  11. 11. Create the Jenkins Pipeline job
  12. 12. Build and inspect the pipeline
  13. 13. Verify pods and services
  14. 14. Open the NodePort application
  15. 15. Test a rolling update
  16. 16. Roll back a failed release
1

Prepare the Kubernetes EC2 instance

Use a separate Ubuntu 24.04 EC2 instance for Kubernetes. Keep Jenkins on its own machine; do not run both on a 909 MiB instance. Use kubeadm, containerd, Flannel, and a NodePort service.

Verify the cluster
kubectl get nodes
kubectl create namespace flask-app
kubectl get namespaces
2

Add the Kubernetes manifest

In github.com/Nerd503/python-flask-pipeline, create k8s/flask-app.yaml. The existing app uses app.py, port 5000, and /health.

k8s/flask-app.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-app
  namespace: flask-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: flask-app
  template:
    metadata:
      labels:
        app: flask-app
    spec:
      containers:
        - name: flask-app
          image: IMAGE:6
          imagePullPolicy: Always
          ports:
            - containerPort: 5000
          readinessProbe:
            httpGet:
              path: /health
              port: 5000
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: 5000
            initialDelaySeconds: 15
            periodSeconds: 20
          resources:
            requests:
              memory: "128Mi"
              cpu: "100m"
            limits:
              memory: "512Mi"
              cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
  name: flask-service
  namespace: flask-app
spec:
  type: NodePort
  selector:
    app: flask-app
  ports:
    - port: 80
      targetPort: 5000
      nodePort: 30080
3

Add and modify the Jenkinsfile

In the root of github.com/Nerd503/python-flask-pipeline, create Jenkinsfile. Students can modify the image name, Docker Hub credential ID, Kubernetes host credential ID, namespace, and deployment name for their own EC2 lab.

Jenkinsfile
pipeline {
  agent any

  environment {
    IMAGE = "YOUR_DOCKERHUB_USERNAME/python-flask-pipeline"
    IMAGE_TAG = "${BUILD_NUMBER}"
    NAMESPACE = "flask-app"
    K8S_HOST = "k8s-ec2-ssh"
  }

  stages {
    stage("Checkout") {
      steps {
        git branch: "main", url: "https://github.com/Nerd503/python-flask-pipeline.git"
      }
    }

    stage("Build") {
      steps {
        sh "docker build -t ${IMAGE}:${IMAGE_TAG} ."
      }
    }

    stage("Test") {
      steps {
        sh "docker run -d --name flask-test -p 5001:5000 ${IMAGE}:${IMAGE_TAG}"
        sh "sleep 5 && curl --fail http://127.0.0.1:5001/health"
      }
      post {
        always {
          sh "docker rm -f flask-test || true"
        }
      }
    }

    stage("Push") {
      steps {
        withCredentials([usernamePassword(credentialsId: "dockerhub-cred", usernameVariable: "DOCKER_USER", passwordVariable: "DOCKER_TOKEN")]) {
          sh "echo ${DOCKER_TOKEN} | docker login -u ${DOCKER_USER} --password-stdin"
          sh "docker push ${IMAGE}:${IMAGE_TAG}"
        }
      }
    }

    stage("Deploy to Kubernetes") {
      steps {
        sshagent([K8S_HOST]) {
          sh "ssh -o StrictHostKeyChecking=no ubuntu@${K8S_HOST} \"kubectl -n ${NAMESPACE} set image deployment/flask-app flask-app=${IMAGE}:${IMAGE_TAG} && kubectl -n ${NAMESPACE} rollout status deployment/flask-app\""
        }
      }
    }
  }
}
4

Test the deployment manually

Apply the manifest and confirm two pods, the service, and the rollout before adding Jenkins.

Kubernetes EC2
kubectl apply -f k8s/flask-app.yaml
kubectl get deployments -n flask-app
kubectl get pods -n flask-app -o wide
kubectl get services -n flask-app
kubectl rollout status deployment/flask-app -n flask-app
curl http://localhost:30080/health
5

Connect Jenkins to Kubernetes

Allow SSH port 22 only from the Jenkins security group. Allow NodePort 30080 from your trusted IP; do not expose 6443 publicly. Generate /var/lib/jenkins/.ssh/k8s_deploy, add its public key to the Kubernetes EC2 ubuntu user, then save the private key in Jenkins as k8s-ec2-ssh with SSH host-key verification enabled.

Jenkins EC2
sudo -u jenkins mkdir -p /var/lib/jenkins/.ssh
sudo -u jenkins ssh-keygen -t ed25519 -N "" -f /var/lib/jenkins/.ssh/k8s_deploy
sudo cat /var/lib/jenkins/.ssh/k8s_deploy.pub
5

Configure the Jenkins pipeline

Keep the existing job name flaskpipeline, GitHub repository https://github.com/Nerd503/python-flask-pipeline.git, branch */main, and credential ID dockerhub-cred. The pipeline should checkout, build, test on port 5001, push the versioned image, then copy the manifest and run kubectl set image over SSH.

Pipeline stages
Checkout
Build Docker Image
Test Flask Application
Push Docker Image
Deploy to Kubernetes
6

Verify rollout and rollback

Permit TCP 30080 from your IP, then test the public NodePort. Kubernetes uses containerd to run the image; Docker is only used by Jenkins to build and push it.

Verify from your Mac
kubectl get pods -n flask-app
kubectl get deployments -n flask-app
kubectl get services -n flask-app
kubectl rollout history deployment/flask-app -n flask-app
curl http://YOUR_KUBERNETES_PUBLIC_IP:30080/health
kubectl rollout undo deployment/flask-app -n flask-app