Hey, there!! Do you wanna deploy your flask Api on GCP(Google Cloud Platform)? Here are simple and easy steps.
Step 1: Set Up Your Flask Application
Ensure your Flask application has the following structure:
/flask-app
āāā app.py # Your main Flask application
āāā requirements.txt # Python dependencies
āāā Dockerfile # Docker configuration
Example app.py:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
@app.route('/api', methods=['POST'])
def api():
data = request.get_json()
return jsonify({"message": "Data received", "data": data}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Example requirements.txt:
# Step 1: Use Python base image
FROM python:3.10-slim
# Step 2: Set working directory
WORKDIR /app
# Step 3: Copy application files
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Step 4: Expose the port and specify the startup command
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "app:app"]
Step 2: Create an Artifact Registry Repository
Enable Artifact Registry in your Google Cloud project:
gcloud services enable artifactregistry.googleapis.com
Create a Docker repository in Artifact Registry:
gcloud artifacts repositories create flask-repo \
--repository-format=docker \
--location=us-central1 \
--description="Repository for Flask application"
- Authenticate Docker with Artifact Registry:
gcloud auth configure-docker us-central1-docker.pkg.dev
Step 3: Build and Push the Docker Image
Build the Docker image:
docker build -t us-central1-docker.pkg.dev/<PROJECT_ID>/flask-repo/flask-app:v1 .
Replace with your Google Cloud project ID.Push the Docker image to Artifact Registry:
docker push us-central1-docker.pkg.dev/<PROJECT_ID>/flask-repo/flask-app:v1
Step 4: Deploy to Cloud Run
- Deploy the image to Cloud Run:
gcloud run deploy flask-app \
--image us-central1-docker.pkg.dev/<PROJECT_ID>/flask-repo/flask-app:v1 \
--platform managed \
--region us-central1 \
--allow-unauthenticated
- Note the URL provided after deployment. Your Flask app will now be accessible via this URL.
Step 5: Verify the Deployment
Access the Application: Visit the Cloud Run service URL in your browser or use curl:
curl https://<CLOUD_RUN_SERVICE_URL>
Check Logs: If anything goes wrong, inspect the logs:
gcloud logs read --platform run --region us-central1 --service flask-app
Step 6: Clean Up (Optional)
If you no longer need the service, delete it to avoid unnecessary charges:
gcloud run services delete flask-app --region us-central1
These steps ensure a smooth workflow for deploying Flask applications to Google Cloud Run with Artifact Registry. Thank You!!
Top comments (0)