Google Cloud Run is a fully managed, serverless platform for running containers. Below is a step-by-step guide to deploy your app to GCP:

1. Prerequisites

  1. Google Cloud Account:

    Ensure you have a Google Cloud account and have set up a project.

  2. Install the Google Cloud SDK:

    If you haven’t installed it yet, follow the instructions for your OS:

  3. Enable Required APIs:

    Enable the following APIs in your GCP project:

    Use the following command or do it via the Google Cloud Console:

    gcloud services enable run.googleapis.com containerregistry.googleapis.com cloudbuild.googleapis.com
    
  4. Authenticate and Set Project:

    Log in and set the active project:

gcloud auth login
gcloud config set project <PROJECT_ID>

2. Create your Flask App

First, set up a basic Flask app if you don’t already have one. Create the following structure:

flask-docker-app/ ├── app.py ├── requirements.txt ├── Dockerfile

app.py: A simple Flask API that connects to the MySQL database and returns rows from a sample table

from flask import Flask, jsonify
import os
import mysql.connector

app = Flask(__name__)

# Load environment variables
DB_HOST = os.environ.get("DB_HOST", "localhost")
DB_USER = os.environ.get("DB_USER", "myuser")
DB_PASSWORD = os.environ.get("DB_PASSWORD", "mypassword")
DB_NAME = os.environ.get("DB_NAME", "mydatabase")

def get_db_connection():
    return mysql.connector.connect(
        host=DB_HOST,
        user=DB_USER,
        password=DB_PASSWORD,
        database=DB_NAME
    )

@app.route("/users", methods=["GET"])
def get_users():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM users;")
    rows = cursor.fetchall()
    cursor.close()
    conn.close()
    return jsonify(rows), 200

@app.route("/", methods=["GET"])
def index():
    return "Welcome to the Flask MySQL API", 200

if __name__ == "__main__":
    # For local testing
    app.run(host="0.0.0.0", port=8080)

Create the requirements file: Create a requirements.txt file to list dependencies:

Flask==2.2.5
mysql-connector-python==8.0.33
gunicorn==20.1.0