Deploying Python Applications to Google Cloud Run

Sherin
python google-cloud docker deployment cloud-run

Deploying to Google Cloud Run

Google Cloud Run is a fully managed compute platform that automatically scales your containerized applications. It's perfect for web applications, APIs, and microservices.

Why Google Cloud Run?

Cloud Run offers several compelling advantages:

  • Serverless: No infrastructure management
  • Auto-scaling: Scales to zero when not in use
  • Cost-effective: Pay only for what you use
  • Fast deployment: Deploy in seconds
  • Any language: Run any containerized application

Prerequisites

Before we begin, you'll need:

  1. A Google Cloud account
  2. gcloud CLI installed
  3. A Dockerized application

Step 1: Containerize Your Application

Create a Dockerfile:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app

Step 2: Set Up Google Cloud

Authenticate with Google Cloud:

gcloud auth login
gcloud config set project sherinxyz-475720

Enable required APIs:

gcloud services enable run.googleapis.com
gcloud services enable containerregistry.googleapis.com

Step 3: Deploy to Cloud Run

Deploy your application:

gcloud run deploy my-app \
  --source . \
  --region us-central1 \
  --allow-unauthenticated \
  --memory 512Mi

That's it! Cloud Run will:
1. Build your container
2. Push it to Container Registry
3. Deploy it
4. Provide you with a URL

Step 4: Custom Domain (Optional)

Map a custom domain:

gcloud run domain-mappings create \
  --service my-app \
  --domain yourdomain.com \
  --region us-central1

Cost Optimization Tips

  1. Set max instances: Prevent unexpected costs
  2. Use smaller containers: Faster cold starts
  3. Optimize memory: Start with 256Mi and adjust
  4. Monitor usage: Use Cloud Monitoring

Example Cloud Run Configuration

You can also use a cloudbuild.yaml for CI/CD:

steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'gcr.io/$PROJECT_ID/my-app', '.']
  - name: 'gcr.io/cloud-builders/docker'
    args: ['push', 'gcr.io/$PROJECT_ID/my-app']
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: gcloud
    args:
      - 'run'
      - 'deploy'
      - 'my-app'
      - '--image'
      - 'gcr.io/$PROJECT_ID/my-app'
      - '--region'
      - 'us-central1'
      - '--platform'
      - 'managed'

Conclusion

Google Cloud Run makes deploying containerized applications incredibly simple. With automatic scaling, built-in monitoring, and a generous free tier, it's an excellent choice for modern web applications.

Give it a try and let me know your experience in the comments!

Leave a Comment

Your comment will be sent directly to me via email. Feel free to share your thoughts!

Comments are sent via email and are not stored on this website.