Automating Python Flask Deployment with Google Cloud Run: A Step-by-Step Guide
Introduction
In today’s digital landscape, automating the deployment of web applications is crucial for businesses and developers. Flask, a popular Python web framework, offers a lightweight and flexible solution for creating web applications. When combined with Google Cloud Run and Google Cloud Build, developers can harness the full potential of these technologies to create robust and scalable applications.
In this step-by-step guide, we will walk you through the process of creating a Flask app, containerizing it with Docker, and deploying it on Google Cloud Run using Google Cloud Build and GitHub triggers. You will learn how to set up a CI/CD pipeline, deploy the Flask app, and handle common issues.
Table of Contents:
- Prerequisites
- Creating the Flask App
- Creating the Dockerfile
- Building and Pushing the Docker Image
- Deploying the App on Google Cloud Run
- Setting Up from a GitHub Repo with Cloud Build Triggers
- Conclusion
Prerequisites
The prerequisites for this project include:
- Flask and Python: Familiarity with Flask, a Python web framework, and Python programming language is essential.
- Google Cloud Platform (GCP) Account: You will need a GCP account to create a project, access the necessary services, and deploy your Flask app on GCP.
- Git and GitHub: Familiarity with the Git version control system and GitHub platform is necessary to clone the project, manage code changes, and set up the CI/CD pipeline using GitHub Actions.
- Docker: Knowledge of Docker and containerization concepts is required to containerize your Flask app using Docker and create Docker images for deployment.
- Google Cloud Build: To configure the CI/CD pipeline for the deployment of the Flask app, one must be familiar with Google Cloud Build, a workflow automation tool.
It is recommended to have a good understanding of these prerequisites before starting the project to ensure a smooth development and deployment process. If you are not familiar with any of these technologies, it is advisable to refer to the respective documentation and tutorials to gain the necessary knowledge.
Creating the Flask App
First, let's create a simple Flask application. Here's the code for
main.py
:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Welcome to Python Flask World v3.0 from cicd'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
This basic Flask app will serve a welcome message at the root URL.
Creating the Dockerfile
Next, we'll create a Dockerfile to containerize our Flask application. Here’s the content of the Dockerfile:
FROM python:3.7-slim
RUN pip install flask
WORKDIR /myapp
COPY main.py /myapp/main.py
CMD ["python", "/myapp/main.py"]
This Dockerfile uses a slim Python image, installs Flask, sets the working directory, copies the main.py file, and specifies the command to run the Flask app.
Building and Pushing the Docker Image
We will use Google Cloud Build to build and push our Docker image. Here’s the cloudbuild.yaml configuration:
steps:
# Build the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/YOUR-PROJECT-NAME/runimage', '.']
# Push the container image to Container Registry
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/YOUR-PROJECT-NAME/runimage']
# Deploy container image to Cloud Run
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args: ['run', 'deploy', 'runwithcicd', '--image', 'gcr.io/devops-442409/runimage', '--region', 'us-central1', '--allow-unauthenticated']
images:
- gcr.io/YOUR-PROJECT-NAME/runimage
options:
logging: CLOUD_LOGGING_ONLY
This configuration file defines the steps to build and push the Docker image to Google Container Registry.
Deploying the App on Google Cloud Run
Finally, we will deploy the Docker image to Google Cloud Run using the following command in our cloudbuild.yaml:
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args: ['run', 'deploy', 'runwithcicd', '--image', 'gcr.io/YOUR-PROJECT-NAME/runimage', '--region', 'us-central1', '--allow-unauthenticated']
This command deploys the Docker image to Cloud Run, making it accessible via a public URL.
Setting Up from a GitHub Repo with Cloud Build Triggers
To automate the deployment process, we will set up a CI/CD pipeline using a GitHub repository and Cloud Build triggers.
GitHub Repository Setup:
Step 1: Create a new repository on GitHub or use an existing one.
Example:
Repository name: flask-cloud-run
Description: A simple Flask app deployed using Google Cloud Run
Step 2: Add your Flask application code (main.py) and Dockerfile to the repository.
Example:
flask-cloud-run/
├── main.py
└── Dockerfile
Step 3: Add the cloudbuild.yaml file to the root of the repository.
Example:
flask-cloud-run/
├── main.py
├── Dockerfile
└── cloudbuild.yaml
Cloud Build Trigger Setup:
Step 1: Open the Google Cloud Console and navigate to Cloud Build.
Step 2: Click on "Triggers" in the left-hand menu and then click "Create Trigger."
Step 3: Configure the trigger:
Name: Give your trigger a meaningful name, such as flask-cloud-run-trigger.
Event: Choose the event that will trigger the build. For example, select "Push to a branch."
Source: Select "GitHub" as the source and connect your GitHub repository.
Branch: Specify the branch to monitor, such as main or master.
Step 4: Set up the build configuration:
Build Configuration: Choose "cloudbuild.yaml" as the build configuration file.
Step 5: Save and create the trigger.
Now, whenever you push changes to the specified branch in your GitHub repository, Cloud Build will automatically start the build process.
For a successful Cloud Run deployment via Cloud Build, I granted these key permissions:
Cloud Build service account needed:
roles/run.admin (Cloud Run Admin)
roles/iam.serviceAccountUser (Service Account User)
Critical Permission Added:
Granted iam.serviceAccounts.actAs permission on the Compute Engine default service account
Conclusion
By following these steps, you can automate the deployment of your Python Flask application using Google Cloud Run. This CI/CD pipeline ensures that your application is always up-to-date and easily scalable. Try it out and let me know how it works for you!
Top comments (0)