DEV Community

Pratik Nalawade
Pratik Nalawade

Posted on

Jenkins Zero to hero I of 5

Getting Started with Jenkins: Building and Running a Flask App in a Jenkins Pipeline

Jenkins is a powerful automation tool used for continuous integration and continuous delivery (CI/CD). It enables developers to automate the process of building, testing, and deploying their applications. In this blog, we’ll walk through setting up a Jenkins pipeline to build and run a simple Flask application.

By the end of this tutorial, you’ll be able to:

  • Set up a Jenkins pipeline.
  • Automate a Python Flask app build.
  • Run the Flask app as part of your pipeline.

Prerequisites

Before we get started, make sure you have:

  1. A Jenkins instance set up. You can install Jenkins locally or use a cloud provider (e.g., AWS, Azure, DigitalOcean).
  2. Basic knowledge of Python and Flask.
  3. A GitHub repository with your Flask app.

Step 1: Install and Set Up Jenkins

First, you need a Jenkins server. If you haven't set up Jenkins yet, follow the official installation guide. Once installed, access Jenkins via http://localhost:8080 or the public IP of your server.

Step 2: Create a Simple Flask Application

Here’s a basic Flask app you can use. If you don’t already have one, you can create a new file app.py with the following content:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Jenkins with Flask!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
Enter fullscreen mode Exit fullscreen mode

If you’re using a virtual environment, don’t forget to activate it and install Flask:

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a GitHub Repository

Push your Flask app to a GitHub repository. You can create a new repository and upload the app.py file. This will allow Jenkins to pull the code and build the app as part of the pipeline.

Step 4: Set Up a Jenkins Pipeline Job

Now, let's create a Jenkins pipeline to automate the build and run process for the Flask app.

  1. Create a New Pipeline Job:

    • Go to Jenkins Dashboard → Click on New Item.
    • Enter the project name (e.g., FlaskAppPipeline).
    • Select Pipeline as the project type and click OK.
  2. Configure Pipeline:

    • Scroll down to the Pipeline section.
    • In the Definition dropdown, select Pipeline script.
  3. Define the Jenkinsfile Script:
    In the pipeline script box, add the following code:

   pipeline {
       agent any

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

           stage('Build Flask App') {
               steps {
                   script {
                       // Create a virtual environment and install Flask
                       sh '''
                       python3 -m venv venv
                       . venv/bin/activate
                       pip install Flask
                       '''
                   }
               }
           }

           stage('Run Flask App') {
               steps {
                   script {
                       // Run Flask app in the background
                       sh '''
                       . venv/bin/activate
                       flask run --host=0.0.0.0 --port=5000 &
                       FLASK_PID=$!
                       sleep 5  # Wait for the app to start
                       kill $FLASK_PID  # Kill the Flask app after testing
                       '''
                   }
               }
           }
       }
   }
Enter fullscreen mode Exit fullscreen mode

This script will:

  • Clone the Flask app from your GitHub repository.
  • Set up a Python virtual environment and install Flask.
  • Run the Flask app in the background, test it, and then terminate the process.

Step 5: Triggering a Build

To trigger the build, you can manually click Build Now from the Jenkins job page or set up a webhook on GitHub to automatically trigger the build on every code commit.

  1. Manual Build:

    • After creating the pipeline, click Build Now to start the process.
  2. Automatic Trigger via GitHub Webhooks:

    • In your GitHub repository, go to SettingsWebhooksAdd webhook.
    • Enter your Jenkins server URL followed by /github-webhook/ (e.g., http://<your-jenkins-server>/github-webhook/).
    • Select application/json as the content type and choose the events that trigger a webhook (usually push events).

Once you’ve configured the webhook, Jenkins will automatically build your project every time you push code to GitHub.

Step 6: Running Flask in the Background

One key step is running the Flask app in the background to avoid blocking the Jenkins build process. In our pipeline, we use the & symbol to run the Flask app in the background, followed by capturing its process ID (FLASK_PID). This allows us to test or deploy the app as needed and stop the app when we’re done by killing the process.

Step 7: Check Build Logs

After running the build, you can check the Jenkins console output to verify that the Flask app was successfully built and run. Go to the job’s page in Jenkins and click on the latest build number to view the log.


Troubleshooting Common Issues

  1. Build Stuck: If the build hangs, ensure that you’re running the Flask app in the background (flask run &). Jenkins will wait for all foreground processes to complete, so it’s important to run long-running processes like Flask as background tasks.

  2. Python Not Found: If Jenkins can’t find Python, make sure it’s installed and added to the system’s PATH. You may also need to install Python 3 and pip on your Jenkins machine if they are not available.

  3. Port Accessibility: If your Flask app doesn’t seem accessible, make sure that the Jenkins server allows traffic on the specified port (e.g., 5000). This is especially important when running Jenkins on cloud instances like AWS.


Conclusion

By following these steps, you’ve successfully set up a Jenkins pipeline that automates the build and execution of a Flask application. Jenkins pipelines are a great way to streamline your development workflow by automating repetitive tasks and ensuring consistent deployment processes.

With this knowledge, you can now experiment further, adding stages for testing, packaging, and deploying your Flask application. In future projects, you might also consider integrating Docker, Kubernetes, or other CI/CD tools to expand your automation capabilities.

Top comments (0)