Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🔧 GCP Account Setup⚙️ GCP Compute Overview🚀 Cloud Run Deployment🎯 App Engine Deployment📁 GCP Storage & Hosting🔥 Firebase Hosting🗄️ Firestore Setup⚡ Firestore Realtime💾 Cloud SQL Setup📊 GCP Monitoring🔑 GCP Authentication📈 GCP Scaling & Performance⚡ Firebase Functions💰 GCP Cost Optimization
Cloud/Gcp Deployment/Cloud Run Deployment

🚀 Cloud Run Deployment

Introduction

Cloud Run is a fully managed serverless platform that lets you run containerized applications with automatic scaling. You pay only for the time your code is running, making it cost-effective for variable workloads and perfect for APIs, microservices, and web applications.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • How to containerize applications with Docker
  • Building and pushing images to Google Container Registry
  • Deploying applications to Cloud Run
  • Configuring environment variables and secrets
  • Understanding Cloud Run's execution model and constraints
  • Monitoring and debugging deployed services

Prerequisites

Ensure you have:

  • Docker installed on your machine
  • gcloud CLI configured with your project
  • Cloud Run API enabled (`gcloud services enable run.googleapis.com`)
  • A containerized application or willingness to follow our examples

Step 1: Create a Simple Application

Node.js Example

Create a new directory and add these files:

package.json:

{
  "name": "hello-cloud-run",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.18.0"
  }
}

index.js:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 8080;

app.get('/', (req, res) => {
  res.json({
    message: 'Hello from Cloud Run!',
    timestamp: new Date().toISOString()
  });
});

app.get('/health', (req, res) => {
  res.json({ status: 'healthy' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Step 2: Create a Dockerfile

The Dockerfile tells Docker how to build your container image.

FROM node:16-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install production dependencies
RUN npm ci --only=production

# Copy application code
COPY . .

EXPOSE 8080

CMD ["npm", "start"]

Key points:

  • `FROM node:16-alpine` - Start with official Node.js image
  • `WORKDIR /app` - Set working directory inside container
  • `npm ci --only=production` - Install only production dependencies (faster, cleaner)
  • `EXPOSE 8080` - Document which port your app uses
  • `CMD` - Command to run when container starts

Step 3: Build Your Docker Image

# Navigate to your project directory
cd my-cloud-run-app

# Build the image
docker build -t hello-cloud-run:latest .

# Test locally before deploying (optional)
docker run -p 8080:8080 hello-cloud-run:latest

# Visit http://localhost:8080 in your browser

Step 4: Push to Container Registry

Google Container Registry (GCR) stores your Docker images.

# Configure Docker to authenticate with GCR
gcloud auth configure-docker

# Tag your image for GCR
docker tag hello-cloud-run:latest gcr.io/PROJECT_ID/hello-cloud-run:latest

# Push the image
docker push gcr.io/PROJECT_ID/hello-cloud-run:latest

# Verify the image was pushed
gcloud container images list

Replace PROJECT_ID with your actual GCP project ID.

Step 5: Deploy to Cloud Run

Basic Deployment (One Command!)

gcloud run deploy hello-cloud-run \\
    --image gcr.io/PROJECT_ID/hello-cloud-run:latest \\
    --platform managed \\
    --region us-central1 \\
    --allow-unauthenticated

Deployment with Configuration

For more control, specify additional parameters:

gcloud run deploy hello-cloud-run \\
    --image gcr.io/PROJECT_ID/hello-cloud-run:latest \\
    --platform managed \\
    --region us-central1 \\
    --allow-unauthenticated \\
    --memory 512M \\
    --cpu 1 \\
    --timeout 600 \\
    --max-instances 50 \\
    --set-env-vars "LOG_LEVEL=info,ENVIRONMENT=production"

Parameters explained:

  • `--image` - Image URL from Container Registry
  • `--platform managed` - Use Google-managed Cloud Run
  • `--region` - GCP region (us-central1, europe-west1, etc.)
  • `--allow-unauthenticated` - Allow public access
  • `--memory` - RAM allocated (128M to 8G)
  • `--cpu` - CPU cores (1 or 2 for standard)
  • `--timeout` - Maximum request duration in seconds
  • `--max-instances` - Maximum number of instances
  • `--set-env-vars` - Environment variables for your app

Step 6: Access Your Service

After deployment completes, you'll see a URL like:

https://hello-cloud-run-xxxxx-us-central1.a.run.app
# Get your service URL
gcloud run services describe hello-cloud-run \\
    --region us-central1 \\
    --format='value(status.url)'

# Test your service
curl https://hello-cloud-run-xxxxx-us-central1.a.run.app/

Important Container Requirements

Your container MUST follow these rules:

1. Listen on PORT Environment Variable

const PORT = process.env.PORT || 8080;
app.listen(PORT);

Cloud Run sets the PORT environment variable automatically. Your app must use it.

2. Handle SIGTERM Signal (Graceful Shutdown)

process.on('SIGTERM', () => {
  console.log('Received SIGTERM, shutting down');
  server.close(() => process.exit(0));
});

Cloud Run sends SIGTERM when shutting down instances. Respond gracefully.

3. Be Stateless

  • Don't rely on local file storage (files won't persist)
  • Use Cloud Storage for files
  • Use Cloud Firestore or Cloud SQL for data
  • Use Cloud Memorystore for caching

4. Start Quickly

  • Container must start within 4 minutes
  • Keep Docker image size small
  • Multi-stage builds help reduce image size

5. Respond to Requests

  • Default timeout: 60 seconds
  • Maximum timeout: 3600 seconds (1 hour)
  • Must respond within timeout period

Environment Variables and Secrets

Simple Environment Variables

gcloud run services update hello-cloud-run \\
    --set-env-vars DATABASE_URL=postgres://...,LOG_LEVEL=debug \\
    --region us-central1

Using Cloud Secret Manager (Recommended)

For sensitive data like API keys and passwords:

# Create a secret
echo "my-secure-password" | gcloud secrets create db-password --data-file=-

# Grant Cloud Run service account access
gcloud secrets add-iam-policy-binding db-password \\
    --member=serviceAccount:PROJECT_ID@appspot.gserviceaccount.com \\
    --role=roles/secretmanager.secretAccessor

# Reference in deployment
gcloud run deploy hello-cloud-run \\
    --image gcr.io/PROJECT_ID/hello-cloud-run:latest \\
    --set-env-vars DB_PASSWORD=/run/secrets/db-password \\
    --region us-central1

Viewing Logs and Debugging

# View last 50 lines of logs
gcloud run logs read hello-cloud-run --limit 50

# Stream logs in real-time
gcloud run logs read hello-cloud-run --follow

# View logs from specific time
gcloud run logs read hello-cloud-run \\
    --start-time=2024-01-15T10:00:00Z \\
    --end-time=2024-01-15T11:00:00Z

Common Issues

Service won't start:

  • Check logs: `gcloud run logs read SERVICE_NAME`
  • Verify PORT is set correctly in your code
  • Check Dockerfile EXPOSE port matches application

Out of memory errors:

  • Increase memory: `--memory 1G` (up to 8G)
  • Check for memory leaks in application

Timeout errors:

  • Increase timeout: `--timeout 300` (seconds)
  • Optimize slow operations
  • Use async operations

Container image too large:

  • Use multi-stage Docker builds
  • Exclude unnecessary files (use .dockerignore)
  • Use alpine base images instead of full distributions

Key Takeaways

  • **Simple Deployment**: One gcloud command deploys your container
  • **Automatic Scaling**: Scales from zero to thousands based on traffic
  • **Cost-Effective**: Pay only for requests, no idle costs
  • **Stateless Design**: Use external services for persistence
  • **Port Listening**: Container must listen on PORT environment variable
  • **Graceful Shutdown**: Handle SIGTERM for clean shutdowns
  • **Environment Variables**: Use for configuration, secrets for sensitive data

Next Steps

1. Deploy your first service

2. Configure environment variables for your application

3. Set up Cloud Secret Manager for sensitive data

4. Explore advanced configurations in the advanced lesson

5. Learn about monitoring and debugging in the monitoring lesson


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn