How to Deploy Rust Applications to Google Cloud Functions

You cannot deploy a standard Rust binary directly to Google Cloud Functions because the platform only supports specific runtimes (Node.js, Python, Go, etc.) or container images.

You cannot deploy a standard Rust binary directly to Google Cloud Functions because the platform only supports specific runtimes (Node.js, Python, Go, etc.) or container images. To run Rust, you must compile your code into a static binary, wrap it in a Docker container, and deploy that container as a Cloud Run service or a Cloud Function 2nd Gen.

The most robust approach is using Cloud Run, which offers better performance and flexibility for compiled languages. First, create a Dockerfile that uses a multi-stage build to keep the image small. This ensures you compile the Rust binary in a build stage and copy only the executable to a lightweight runtime stage.

# Stage 1: Build
FROM rust:1.75-slim AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY . .
RUN cargo build --release --bin my-function

# Stage 2: Runtime
FROM gcr.io/distroless/cc-debian11
WORKDIR /app
COPY --from=builder /app/target/release/my-function .
CMD ["./my-function"]

Your Rust application must act as an HTTP server listening on the port defined by the PORT environment variable (default 8080). Use a lightweight framework like actix-web or axum. Here is a minimal main.rs example using actix-web:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello from Rust on GCP!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    let host = "0.0.0.0";
    
    println!("Starting server on {}:{}", host, port);
    
    HttpServer::new(|| {
        App::new().route("/", web::get().to(index))
    })
    .bind((host, port.parse().unwrap()))?
    .run()
    .await
}

Once your Dockerfile and code are ready, build and push the image to Google Artifact Registry, then deploy it. You can do this entirely via the gcloud CLI:

# Set your project and region
export PROJECT_ID="your-project-id"
export REGION="us-central1"
export SERVICE_NAME="rust-function"

# Build and push the container
gcloud builds submit --tag gcr.io/$PROJECT_ID/$SERVICE_NAME

# Deploy to Cloud Run (which acts as the serverless function)
gcloud run deploy $SERVICE_NAME \
  --image gcr.io/$PROJECT_ID/$SERVICE_NAME \
  --region $REGION \
  --platform managed \
  --allow-unauthenticated

If you specifically need the "Cloud Functions" namespace (e.g., for tight integration with other GCP triggers), use Cloud Functions 2nd Gen. The process is identical to Cloud Run, but you use gcloud functions deploy with the --gen2 flag and specify the container image. Note that Cloud Functions 1st Gen does not support custom containers, so you must use 2nd Gen or Cloud Run for any Rust deployment.