Google Cloud Run example using Python Flask
Overview
Hey there!
This codelab will walk you through the process of creating a simple "Hello World" application using Python Flask and deploying it to Google Cloud Run.
Requirements
In order to follow this codelab, you'll need the following:
- A Google Cloud Platform account.
- Google Cloud CLI installed and initialized.
- Python installed locally.
Setting Up Your Google Cloud Account
- Head over to Google Cloud Platform and create an account.
- Enable billing
- Create a new project, let's name it
project-x.
Install Google Cloud CLI
Follow the official guide to install the Google Cloud CLI: Installing Google Cloud SDK.
Create and Run the Flask Application
Create a file named main.py with the following content:
from flask import Flask
import os
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
Install Flask:
pip install Flask
Create a Python virtual environment and activate it:
python3 -m venv .venv
source .venv/bin/activate
Set up a new directory for your project:
mkdir hello-world-cloud-run
cd hello-world-cloud-run
Running the App Locally
- Open your web browser and go to
http://localhost:8080. You should see the "Hello, World!" message.
Run your application locally:
python main.py
Deploy to Google Cloud Run
- Wait for the deployment to complete. You will receive a URL where your application is live.
Deploy your application to Google Cloud Run:
gcloud run deploy
Generate the requirements.txt file
pip list --format=freeze > requirements.txt
Conclusion
Congratulations! You've just built and deployed a simple application on Google Cloud Run using Python and Flask!
What's Next?
- Experiment with adding more routes and functionalities to your Flask application.
- Learn more about managing and monitoring your applications on Google Cloud Run.
- Explore other Google Cloud services that can enhance your application.