Cloud Run Samples

repository·main·Indexed 43 days ago

https://github.com/googlecloudplatform/cloud-run-samples

A collection of sample applications and code snippets for Google Cloud Run. Includes implementations for hosting GitHub runners with worker pools, GPU-accelerated video transcoding with FFmpeg, multi-container services using Nginx and Secret Manager, VPC egress configurations, and various quickstarts for Go, Node.js, Python, and Java.

Tokens
5.8K
Snippets
24
Records
32
Agent score
55%

What's inside Cloud Run Samples

  1. GPU-Accelerated Video Transcoding with FFmpeg on Cloud Run Jobs

    main

    This sample demonstrates how to perform low-priority, offline video transcoding using FFmpeg with NVIDIA NVENC acceleration on Google Cloud Run Jobs. It is designed to handle batch transcoding of videos up to 8GiB in size.

    For a detailed step-by-step walkthrough, refer to the official Google Cloud tutorial: GPU-accelerated video transcoding with FFmpeg on Cloud Run jobs.

  2. Explore Cloud Run sample categories

    main

    This repository provides samples for various Cloud Run scenarios. Key categories include:

    • Quickstarts: Hello World services and jobs across multiple languages (Go, Node.js, Python, Java, etc.).
    • Logging & Observability: Manual structured logging without client libraries.
    • Infrastructure & Networking: Using system-installed binaries, VPC egress/ingress settings, and multi-container setups (e.g., with Nginx).
    • Integrations: Pub/Sub push subscriptions, Cloud SQL (MySQL and Postgres), and event-driven image processing.
    • Security & Auth: End-user authentication with Identity Platform, service-to-service authenticated requests using ID tokens, and gRPC service-to-service communication.
    • Performance Optimization: Using global state for in-memory caching and lazy initialization to reduce cold start times.
    • Troubleshooting: A "Hello Broken" service designed specifically for testing error handling and troubleshooting.
  3. Build and deploy a Cloud Run service with VPC egress

    main

    To call a network-restricted function, deploy a Cloud Run service configured to route all egress traffic through a VPC connector.

    1. Set your Artifact Registry repository variable:
    export _AR_REPO_NAME=us-central1-pkg.dev/${PROJECT_ID}/containers
    1. Build the container image:
    gcloud builds submit --tag=${_AR_REPO_NAME}/restricted-function-caller .
    1. Deploy to Cloud Run: Use --vpc-egress=all to ensure all traffic is routed through the connector, and specify the --vpc-connector name. Provide the URL of the restricted function via the URL environment variable.

    Run this from inside the vpc-sample directory:

    gcloud run deploy run-function --image ${_AR_REPO_NAME}/restricted-function-caller \
    --no-allow-unauthenticated \
    --update-env-vars=URL=https://${_SERVICE_REGION}-$PROJECT_ID.cloudfunctions.net/restricted-function-caller \
    --vpc-egress=all --vpc-connector=serverless-connector --region=${_SERVICE_REGION}
  4. Build the Cloud Run jobs shell sample

    main

    To build the container image for this sample, you must first set your Google Cloud Project ID and your Artifact Registry repository path as environment variables. Then, use Cloud Build to submit the build to Google Cloud.

    export GOOGLE_CLOUD_PROJECT=<PROJECT_ID>
    export AR_REPO_NAME=us-central1-pkg.dev/${GOOGLE_CLOUD_PROJECT}/containers
    
    gcloud builds submit -t "${AR_REPO_NAME}/jobs-shell"
  5. Create a Serverless VPC Access connector

    main

    A Serverless VPC Access connector is required to allow Cloud Run or Cloud Functions to send traffic through a VPC network. Use the gcloud compute networks vpc-access connectors create command. Ensure you specify a --range that does not overlap with existing IP ranges in your VPC.

    gcloud compute networks vpc-access connectors create serverless-connector \
    --region=${_SERVICE_REGION} --range=10.8.0.0/28
  6. Create a Cloud Run job

    main

    Use the gcloud run jobs create command to deploy the shell sample to Cloud Run. You can configure the number of tasks, retry logic, and environment variables for the job execution.

    gcloud run jobs create jobs-shell \
      --set-env-vars FAIL_RATE=0.4,SLEEP_MS=5000 \
      --max-retries 10 \
      --tasks 5 \
      --image "${AR_REPO_NAME}/jobs-shell"
  7. Deploy a network-restricted Cloud Function

    main

    Deploy a Cloud Function with --ingress-settings=internal-only to restrict access so that only services within your project can call it. This prevents public internet access to the function.

    Run this command from inside the vpc-sample directory:

    gcloud functions deploy restricted-function \
    --runtime=python311 --trigger-http --no-allow-unauthenticated \
    --ingress-settings=internal-only --entry-point=hello_world
  8. Test and allow unauthenticated access to your Cloud Run service

    main

    Authenticated Requests

    To test the service with an identity token:

    curl --header "Authorization: Bearer $(gcloud auth print-identity-token)" <cloud-run-mc-service-url>

    Allow Unauthenticated Access

    To make the service publicly accessible to anyone (allUsers):

    gcloud run services add-iam-policy-binding $MC_SERVICE_NAME \
        --member="allUsers" \
        --role="roles/run.invoker"

    Once unauthenticated access is allowed, you can access the service via a simple curl:

    curl <cloud-run-mc-service-url>
    # Authenticated
    curl --header "Authorization: Bearer $(gcloud auth print-identity-token)" <cloud-run-mc-service-url>
    
    # Allow unauthenticated
    gcloud run services add-iam-policy-binding $MC_SERVICE_NAME \
        --member="allUsers" \
        --role="roles/run.invoker"
    
    # Unauthenticated
    curl <cloud-run-mc-service-url>
  9. Deploy a multi-container Cloud Run service

    main

    Deploy the service using a service.yaml configuration file. You must substitute the service name and region in the YAML file before deployment.

    1. Set your environment variables:
    export MC_SERVICE_NAME=<service-name>
    export REGION=us-central1
    1. Substitute the variables into service.yaml:
    sed -i -e s/MC_SERVICE_NAME/${MC_SERVICE_NAME}/g -e s/REGION/${REGION}/g service.yaml
    1. Deploy the service:
    gcloud run services replace service.yaml

    Service Architecture

    By default, this deployment includes two containers:

    • nginx: The serving ingress container (entrypoint) listening on port 8080.
    • hello: A sidecar container.

    nginx is configured to proxy requests over to the hello container at port 8888.

    export MC_SERVICE_NAME=<service-name>
    export REGION=us-central1
    
    sed -i -e s/MC_SERVICE_NAME/${MC_SERVICE_NAME}/g -e s/REGION/${REGION}/g service.yaml
    
    gcloud run services replace service.yaml
  10. Add nginx server configuration to Secret Manager

    main

    This sample uses Secret Manager to mount an nginx.conf file as a volume at runtime, separating configuration from the container image. In the service.yaml file, look for the nginx-conf-secret volume mount and the nginx_config secret name references.

    Using gcloud CLI

    1. Create the secret using a local nginx.conf file:
    gcloud secrets create nginx_config --replication-policy="automatic" --data-file="./nginx.conf"
    1. Grant the Compute Engine default service account access to the secret:
    export PROJECT_NUMBER=$(gcloud projects describe $(gcloud config get-value project) --format='value(projectNumber)')
    gcloud secrets add-iam-policy-binding nginx_config --member=serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com --role='roles/secretmanager.secretAccessor'

    Using Google Cloud Console

    1. Go to the Secret Manager UI.
    2. Select + Create Secret.
    3. Name the secret nginx_config.
    4. Provide the contents of your nginx.conf file.
    5. Click Create Secret.
    gcloud secrets create nginx_config --replication-policy="automatic" --data-file="./nginx.conf"
    
    export PROJECT_NUMBER=$(gcloud projects describe $(gcloud config get-value project) --format='value(projectNumber)')
    gcloud secrets add-iam-policy-binding nginx_config --member=serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com --role='roles/secretmanager.secretAccessor'