tutoriales.com

Deploying Serverless Applications with Cloud Run on Google Cloud

This tutorial will guide you step-by-step through deploying serverless applications using Cloud Run on Google Cloud. Discover how to bring your containers to the cloud, configure managed services, and leverage automatic scalability for your projects.

Intermedio18 min de lectura137 views
Reportar error

Google Cloud Run is a serverless compute platform that allows you to run containers without managing the underlying infrastructure. It's an excellent choice for deploying microservices, APIs, web applications, and batch jobs that need to scale rapidly and only pay for what you use.

In this tutorial, we'll explore the key concepts of Cloud Run and guide you through the process of deploying a sample application.


🚀 What is Google Cloud Run?

Cloud Run is a fully managed service that lets you run stateless containers on Google Cloud. This means Google handles all server provisioning, scaling, patching, and management, allowing you to focus solely on your code.

💡 Key Benefits of Cloud Run

  • Serverless: No server management required. Google handles the infrastructure.
  • Containers: Deploy any application packaged as a Docker container, with no language or library restrictions.
  • Pay-per-use: You only pay when your code is running, down to the nearest millisecond of CPU and memory usage.
  • Automatic Scaling: Scales from zero to thousands of instances and back down automatically based on demand.
  • Integration: Seamlessly integrates with other Google Cloud services like Cloud Build, Cloud SQL, VPCs, and more.
  • Custom Domain: Easy mapping of custom domains to your Cloud Run services.
💡 Tip: Cloud Run is ideal for applications with irregular traffic patterns or those requiring rapid scaling, such as RESTful APIs, webhooks, microservices, and mobile backends.

🛠️ Required Tools

Before you begin, make sure you have the following:

  1. A Google Cloud Account: If you don't have one, you can sign up for a free trial that includes generous credits.
  2. Google Cloud SDK (gcloud CLI): Installed and configured on your local machine. This will allow you to interact with Google Cloud from the command line.
    • You can verify the installation with: gcloud --version
    • If you don't have it, follow the installation instructions in the official Google Cloud documentation.
  3. Docker: Installed on your local machine. We'll use it to build our container image.
    • You can verify the installation with: docker --version
📌 Note: This tutorial assumes you have an existing Google Cloud project and that the gcloud CLI is authenticated and configured for that project.

🚀 Step 1: Set Up Your Google Cloud Project

First, ensure that the necessary services are enabled in your project.

1.1 Enable APIs

We need to enable the Cloud Run and Artifact Registry APIs (or Container Registry if you prefer).

gcloud services enable run.googleapis.com
gcloud services enable artifactregistry.googleapis.com
🔥 Important: Artifact Registry is Google's recommended service for storing container images nowadays, surpassing Container Registry. Make sure to use it for new projects.

1.2 Create an Artifact Registry Repository

Let's create a repository in Artifact Registry to store our Docker image. Choose a region that is close to your users or other GCP services you use.

gcloud artifacts repositories create my-cloudrun-repo \
    --repository-format=docker \
    --location=us-central1 \
    --description="Docker repository for Cloud Run images"

Replace my-cloudrun-repo with a unique name for your repository and us-central1 with your preferred region.


💻 Step 2: Create a Sample Application

For this tutorial, we'll use a simple web application written in Python with Flask. This application will respond with a welcome message.

2.1 Project Structure

Create a folder for your project and, inside it, the following files:

my-cloudrun-app/
├── app.py
├── requirements.txt
└── Dockerfile

2.2 app.py

This file will contain the code for our Flask application.

from flask import Flask
import os

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Cloud Run! Greetings from GPT-4o!\n'

if __name__ == '__main__':
    # Get the port from the PORT environment variable, if it doesn't exist, use 8080
    port = int(os.environ.get('PORT', 8080))
    app.run(debug=True, host='0.0.0.0', port=port)
💡 Tip: It's crucial that your application listens on the port specified by the `PORT` environment variable. Cloud Run injects this variable, and if your application doesn't use it, it won't be able to receive traffic.

2.3 requirements.txt

This file will list the Python dependencies.

Flask==2.3.3

2.4 Dockerfile

This file defines how our Docker image will be built.

# Usa una imagen base de Python ligera
FROM python:3.9-slim-buster

# Establece el directorio de trabajo dentro del contenedor
WORKDIR /app

# Copia los archivos de requerimientos e instala las dependencias
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copia el código de tu aplicación
COPY .

# Expone el puerto que usará la aplicación (Cloud Run lo manejará)
EXPOSE 8080

# Comando para ejecutar la aplicación cuando el contenedor se inicie
# Usamos gunicorn para producción, pero para este ejemplo simple, python app.py es suficiente
# CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:$PORT"]
CMD ["python", "app.py"]
⚠️ Warning: For production applications, it's highly recommended to use a WSGI server like Gunicorn or uWSGI with Flask, instead of `python app.py` directly. This offers better performance and stability.

📦 Step 3: Build and Push the Docker Image

Now that we have our application and Dockerfile, we'll build the Docker image and upload it to Artifact Registry.

3.1 Build the Image

Navigate to the my-cloudrun-app folder in your terminal and run the following command. Replace my-cloudrun-repo and us-central1 with your values.

docker build -t us-central1-docker.pkg.dev/YOUR_PROJECT_ID/my-cloudrun-repo/my-cloudrun-app:1.0 .

Make sure to replace YOUR_PROJECT_ID with your Google Cloud project ID.

📌 Note: The image name follows the format `LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY_NAME/IMAGE_NAME:TAG`.

3.2 Authenticate Docker with Artifact Registry

To push the image, Docker needs to authenticate with Artifact Registry. Run:

gcloud auth configure-docker us-central1-docker.pkg.dev

Replace us-central1 with your repository's region.

3.3 Push the Image to Artifact Registry

docker push us-central1-docker.pkg.dev/YOUR_PROJECT_ID/my-cloudrun-repo/my-cloudrun-app:1.0

Verify that the image has been uploaded correctly by visiting the Artifact Registry section in the Google Cloud console, or by listing the images with gcloud artifacts docker images list.


🚀 Step 4: Deploy the Application to Cloud Run

With the container image in Artifact Registry, we are ready to deploy it to Cloud Run.

4.1 Deploy the Service

gcloud run deploy my-cloudrun-service \
    --image us-central1-docker.pkg.dev/YOUR_PROJECT_ID/my-cloudrun-repo/my-cloudrun-app:1.0 \
    --platform managed \
    --region us-central1 \
    --allow-unauthenticated \
    --max-instances 10 \
    --cpu 1 \
    --memory 512Mi \
    --port 8080

Let's break down the arguments:

  • my-cloudrun-service: The name you give your Cloud Run service.
  • --image: Full path to your Docker image in Artifact Registry.
  • --platform managed: Specifies that we'll use the managed version of Cloud Run (the most common and easiest to use).
  • --region: The region where your service will be deployed. It should be the same as your Artifact Registry repository or nearby.
  • --allow-unauthenticated: Allows the service to be invoked without authentication credentials. Ideal for public web applications or APIs.
  • --max-instances: The maximum number of instances Cloud Run can scale for your service. Adjust as needed.
  • --cpu: The amount of vCPU allocated to each instance. A minimum of 1 vCPU is recommended for most web applications.
  • --memory: The amount of memory allocated to each instance. Adjust according to your application's requirements.
  • --port: The port your container listens for traffic on. This must match the EXPOSE in your Dockerfile and the port your Flask application is listening on.

During deployment, the gcloud CLI will ask if you want to create new permissions or if you agree with the configuration. Confirm to continue.

4.2 Verify the Deployment

Once the deployment is complete, the terminal will show you the service URL. Open this URL in your browser. You should see the message: Hello from Cloud Run! Greetings from GPT-4o!

You can also get service details with:

gcloud run services describe my-cloudrun-service --platform managed --region us-central1

This will give you detailed information, including the URL, service status, and scaling configuration.

Deployment Complete ✅

📊 Step 5: Cloud Run Management and Scalability

Cloud Run offers powerful features for managing and scaling your services.

5.1 Adjust Concurrency

Concurrency is the maximum number of simultaneous requests each instance of your service can handle. The default value is 80.

To adjust it, you can use the update command:

gcloud run services update my-cloudrun-service \
    --platform managed \
    --region us-central1 \
    --concurrency 50
💡 Tip: A higher concurrency value can reduce the number of instances needed and, therefore, costs. However, make sure your application can handle that level of concurrency. Perform load tests to find the optimal value.

5.2 Set a Minimum Number of Instances

By default, Cloud Run scales to zero instances when there's no traffic. If you need consistent low startup latency or have specific requirements, you can keep a minimum number of instances always active.

gcloud run services update my-cloudrun-service \
    --platform managed \
    --region us-central1 \
    --min-instances 1

This ensures that at least one instance is always ready to respond to requests, though it will incur an associated cost.

5.3 Custom Domain Mapping

To use your own domain (e.g., api.mysite.com) with Cloud Run, follow these steps:

  1. Add domain mapping:
gcloud run domains add-mapping --service my-cloudrun-service --domain api.mysite.com --platform managed --region us-central1
  1. Update DNS records: Cloud Run will provide you with CNAME or A/AAAA records that you'll need to add to your domain's DNS configuration.
🔥 Important: DNS propagation can take some time (from minutes to several hours).

5.4 Environment Variables

You can inject environment variables into your Cloud Run services for configurations, API keys, etc.

gcloud run services update my-cloudrun-service \
    --platform managed \
    --region us-central1 \
    --set-env-vars ENV_VAR_NAME=value,ANOTHER_VAR=another_value

5.5 Integration with Cloud SQL

If your application needs a database, Cloud Run easily integrates with Cloud SQL. Simply authorize your Cloud Run service to connect to your Cloud SQL instance.

gcloud run services update my-cloudrun-service \
    --platform managed \
    --region us-central1 \
    --add-cloudsql-instances YOUR_CLOUD_SQL_CONNECTION_NAME

Where YOUR_CLOUD_SQL_CONNECTION_NAME is in the format PROJECT_ID:REGION:INSTANCE_NAME.

Application Code Dockerfile Docker Build Artifact Registry Cloud Run Deploy Public URL Cloud Run Deployment Flow

🗑️ Cleaning Up Resources

To avoid unexpected charges, it's good practice to delete resources you no longer need.

  1. Delete the Cloud Run service:
gcloud run services delete my-cloudrun-service --platform managed --region us-central1
  1. Delete the Artifact Registry image:
gcloud artifacts docker images delete us-central1-docker.pkg.dev/YOUR_PROJECT_ID/my-cloudrun-repo/my-cloudrun-app:1.0 --delete-tags --delete-metadata
  1. Delete the Artifact Registry repository (optional):
gcloud artifacts repositories delete my-cloudrun-repo --location=us-central1
  1. Disable APIs (optional):
gcloud services disable run.googleapis.com
gcloud services disable artifactregistry.googleapis.com

❓ Frequently Asked Questions (FAQ)

What is the difference between Cloud Run and App Engine? App Engine is an older, more robust PaaS (Platform as a Service) platform, ideal for monolithic or large applications. Cloud Run is a more modern and flexible service, focused on running serverless containers, ideal for microservices and functions. Cloud Run offers a more granular pay-per-use model and greater flexibility in the execution environment thanks to containers.
Can I run any type of application on Cloud Run? Yes, as long as you can package it as a Docker container and it complies with the Cloud Run "contract" (listen on the port specified by the `PORT` variable, respond to HTTP requests, etc.). This includes applications in any language, frameworks, or even custom binaries.
Is Cloud Run suitable for long-running or CPU-intensive tasks? Cloud Run is designed to respond to HTTP requests. For long-running or CPU-intensive tasks that don't respond to an HTTP request (e.g., batch data processing), services like Cloud Functions (for short, event-driven functions), Cloud Tasks (for work queues), or even a job on Compute Engine/GKE would be more appropriate. However, Cloud Run can be suitable if the task can be contained within the HTTP request timeout (maximum 60 minutes).
How do I handle secrets like API keys in Cloud Run? The best practice is to use Google Secret Manager to store your secrets and access them from your Cloud Run application. You can inject them as environment variables or read them directly from your application code using Secret Manager client libraries. This is much more secure than hardcoding secrets directly into your Docker image or Cloud Run environment variables.

Conclusion ✨

You've completed this tutorial on how to deploy serverless applications with Cloud Run on Google Cloud. You've learned how to build a Docker image, upload it to Artifact Registry, and deploy it as a scalable service on Cloud Run. You've also explored advanced configuration and management options.

Cloud Run is a powerful tool for modernizing your applications and reducing operational overhead. Experiment with different configurations and explore its integrations with other Google Cloud services to take your projects to the next level.

Happy deploying!

Tutoriales relacionados

Comentarios (0)

Aún no hay comentarios. ¡Sé el primero!