Go to console

Serve dynamic content and host microservices with Cloud Run

Pair Cloud Run with Firebase Hosting to generate and serve your dynamic content or build REST APIs as microservices.

Using Cloud Run, you can deploy an application packaged in a container image. Then, using Firebase Hosting, you can direct HTTPS requests to trigger your containerized app.

  • Cloud Run supports several languages (including Go, Node.js, Python, and Java), giving you the flexibility to use the programming language and framework of your choice.
  • Cloud Run automatically and horizontally scales your container image to handle the received requests, then scales down when demand decreases.
  • You only pay for the CPU, memory, and networking consumed during request handling.

For example use cases and samples for Cloud Run integrated with Firebase Hosting, visit our serverless overview.


This guide shows you how to:

  1. Write a simple Hello World application
  2. Containerize an app and upload it to Container Registry
  3. Deploy the container image to Cloud Run
  4. Direct Hosting requests to your containerized app

Note that to improve the performance of serving dynamic content, you can optionally tune your cache settings.

Before you begin

Before using Cloud Run, you need to complete some initial tasks, including setting up a billing account, enabling the Cloud Run API, and installing the gcloud command line tool.

Set up billing for your project

Cloud Run does offer free usage quota, but you still must have a billing account associated with your Firebase project to use or try out Cloud Run.

Enable the API and install the SDK

  1. Enable the Cloud Run API in the Google APIs console:

    1. Open the Cloud Run API page in the Google APIs console.

    2. When prompted, select your Firebase project.

    3. Click Enable on the Cloud Run API page.

  2. Install and initialize the Cloud SDK.

Install the gcloud beta component

  1. Run the following command to install the gcloud beta component:

    gcloud components install beta
  2. Update components:

    gcloud components update
  3. Check that the gcloud tool is configured for the correct project:

    gcloud config list

Step 1: Write the sample application

Note that Cloud Run supports many other languages in addition to the languages shown in the following sample.

Go

  1. Create a new directory named helloworld-go, then change directory into it:

    mkdir helloworld-go
    cd helloworld-go
  2. Create a new file named helloworld.go, then add the following code:

    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	log.Print("Hello world received a request.")
    	target := os.Getenv("TARGET")
    	if target == "" {
    		target = "World"
    	}
    	fmt.Fprintf(w, "Hello %s!\n", target)
    }
    
    func main() {
    	log.Print("Hello world sample started.")
    
    	http.HandleFunc("/", handler)
    
    	port := os.Getenv("PORT")
    	if port == "" {
    		port = "8080"
    	}
    
    	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
    }
    

    This code creates a basic web server that listens on the port defined by the PORT environment variable.

Your app is finished and ready to be containerized and uploaded to Container Registry.

Node.js

  1. Create a new directory named helloworld-nodejs, then change directory into it:

    mkdir helloworld-nodejs
    cd helloworld-nodejs
  2. Create a package.json file with the following contents:

    {
      "name": "knative-serving-helloworld",
      "version": "1.0.0",
      "description": "Simple hello world sample in Node",
      "main": "index.js",
      "scripts": {
        "start": "node index.js"
      },
      "author": "",
      "license": "Apache-2.0",
      "dependencies": {
        "express": "^4.16.4"
      }
    }
    
  3. Create a new file named index.js, then add the following code:

    const express = require('express');
    const app = express();
    
    app.get('/', (req, res) => {
      console.log('Hello world received a request.');
    
      const target = process.env.TARGET || 'World';
      res.send(`Hello ${target}!`);
    });
    
    const port = process.env.PORT || 8080;
    app.listen(port, () => {
      console.log('Hello world listening on port', port);
    });
    

    This code creates a basic web server that listens on the port defined by the PORT environment variable.

Your app is finished and ready to be containerized and uploaded to Container Registry.

Python

  1. Create a new directory named helloworld-python, then change directory into it:

    mkdir helloworld-python
    cd helloworld-python
  2. Create a new file named app.py, then add the following code:

    import os
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        target = os.environ.get('TARGET', 'World')
        return 'Hello {}!\n'.format(target)
    
    if __name__ == "__main__":
        app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
    

    This code creates a basic web server that listens on the port defined by the PORT environment variable.

Your app is finished and ready to be containerized and uploaded to Container Registry.

Java

  1. Install Java SE 8 or later JDK and CURL.

    Note that we only need to do this to create the new web project in the next step. The Dockerfile, which is described later, will load all dependencies into the container.

  2. From the console, create a new empty web project using cURL then unzip commands:

    curl https://start.spring.io/starter.zip \
        -d dependencies=web \
        -d name=helloworld \
        -d artifactId=helloworld \
        -o helloworld.zip
    unzip helloworld.zip
    

    This creates a SpringBoot project.

  3. Update the SpringBootApplication class in src/main/java/com/example/helloworld/HelloworldApplication.java by adding a @RestController to handle the / mapping and also add a @Value field to provide the TARGET environment variable:

    package com.example.helloworld;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    public class HelloworldApplication {
    
    	@Value("${TARGET:World}")
    	String message;
    
    	@RestController
    	class HelloworldController {
    		@GetMapping("/")
    		String hello() {
    			return "Hello " + message + "!";
    		}
    	}
    
    	public static void main(String[] args) {
    		SpringApplication.run(HelloworldApplication.class, args);
    	}
    }
    

    This code creates a basic web server that listens on the port defined by the PORT environment variable.

Your app is finished and ready to be containerized and uploaded to Container Registry.

Step 2: Containerize an app and upload it to Container Registry

  1. Containerize the sample app by creating a new file named Dockerfile in the same directory as the source files. Copy the following content into your file.

    Go

    # Use the offical Golang image to create a build artifact.
    # This is based on Debian and sets the GOPATH to /go.
    # https://hub.docker.com/_/golang
    FROM golang as builder
    
    # Copy local code to the container image.
    WORKDIR /go/src/github.com/knative/docs/helloworld
    COPY . .
    
    # Build the outyet command inside the container.
    # (You may fetch or manage dependencies here,
    # either manually or with a tool like "godep".)
    RUN CGO_ENABLED=0 GOOS=linux go build -v -o helloworld
    
    # Use a Docker multi-stage build to create a lean production image.
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM alpine
    
    # Copy the binary to the production image from the builder stage.
    COPY --from=builder /go/src/github.com/knative/docs/helloworld/helloworld /helloworld
    
    # Service must listen to $PORT environment variable.
    # This default value facilitates local development.
    ENV PORT 8080
    
    # Run the web service on container startup.
    CMD ["/helloworld"]
    

    Node.js

    # Use the official Node.js 10 image.
    # https://hub.docker.com/_/node
    FROM node:10
    
    # Create and change to the app directory.
    WORKDIR /usr/src/app
    
    # Copy application dependency manifests to the container image.
    # A wildcard is used to ensure both package.json AND package-lock.json are copied.
    # Copying this separately prevents re-running npm install on every code change.
    COPY package*.json ./
    
    # Install production dependencies.
    RUN npm install --only=production
    
    # Copy local code to the container image.
    COPY . .
    
    # Service must listen to $PORT environment variable.
    # This default value facilitates local development.
    ENV PORT 8080
    
    # Run the web service on container startup.
    CMD [ "npm", "start" ]
    

    Python

    # Use the official Python image.
    # https://hub.docker.com/_/python
    FROM python
    
    # Copy local code to the container image.
    ENV APP_HOME /app
    WORKDIR $APP_HOME
    COPY . .
    
    # Install production dependencies.
    RUN pip install Flask gunicorn
    
    # Service must listen to $PORT environment variable.
    # This default value facilitates local development.
    ENV PORT 8080
    
    # Run the web service on container startup. Here we use the gunicorn
    # webserver, with one worker process and 8 threads.
    # For environments with multiple CPU cores, increase the number of workers
    # to be equal to the cores available.
    CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 app:app
    

    Java

    # Use the official maven/Java 8 image to create a build artifact.
    # https://hub.docker.com/_/maven
    FROM maven:3.5-jdk-8-alpine as builder
    
    # Copy local code to the container image.
    WORKDIR /app
    COPY pom.xml .
    COPY src ./src
    
    # Build a release artifact.
    RUN mvn package -DskipTests
    
    # Use the Official OpenJDK image for a lean production stage of our multi-stage build.
    # https://hub.docker.com/_/openjdk
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM openjdk:8-jre-alpine
    
    # Copy the jar to the production image from the builder stage.
    COPY --from=builder /app/target/helloworld-*.jar /helloworld.jar
    
    # Service must listen to $PORT environment variable.
    # This default value facilitates local development.
    ENV PORT 8080
    
    # Run the web service on container startup.
    CMD ["java","-Djava.security.egd=file:/dev/./urandom","-Dserver.port=${PORT}","-jar","/helloworld.jar"]
    

  2. Build your container image using Cloud Build by running the following command from the directory containing your Dockerfile:

    gcloud builds submit --tag gcr.io/projectID/helloworld

    Upon success, you will see a SUCCESS message containing the image name
    (gcr.io/projectID/helloworld).

The container image is now stored in Container Registry and can be re-used if desired.

Note that, instead of Cloud Build, you can use a locally installed version of Docker to build your container locally.

Step 3: Deploy the container image to Cloud Run

  1. Deploy using the following command:

    gcloud beta run deploy --image gcr.io/projectID/helloworld

  2. When prompted:

  3. Wait a few moments for the deploy to complete. On success, the command line displays the service URL. For example:

    https://helloworld-random_hash-us-central1.a.run.app
  4. Visit your deployed container by opening the service URL in a web browser.

The next step walks you through how to access this containerized app from a Firebase Hosting URL so that it can generate dynamic content for your Firebase-hosted site.

Step 4: Direct hosting requests to your containerized app

With rewrite rules, you can direct requests that match specific patterns to a single destination.

The following example shows how to direct all requests from the page /helloworld on your Hosting site to trigger the startup and running of your helloworld container instance.

  1. Make sure that:

    For detailed instructions about installing the CLI and initializing Hosting, see the Get Started guide for Hosting.

  2. Open your firebase.json file.

  3. Add the following rewrite configuration under the hosting section:

    "hosting": {
      // ...
    
      // Add the "rewrites" attribute within "hosting"
      "rewrites": [ {
        "source": "**",
        "run": {
          "serviceId": "helloworld",  // "service name" (from when you deployed the container image)
          "region": "us-central1"     // optional (if omitted, default is us-central1)
        }
      } ]
    }
    
  4. Deploy your hosting configuration to your site by running the following command from the root of your project directory:

    firebase deploy

Your container is now reachable via the following URLs:

  • Your Firebase subdomains: projectID.web.app/helloworld and projectID.firebaseapp.com/helloworld

  • Any connected custom domains: custom-domain/helloworld

Visit the Hosting configuration page for more details about rewrite rules. You can also learn about the priority order of responses for various Hosting configurations.

Test locally

During development, you can run and test your container image locally. For detailed instructions, visit the Cloud Run documentation.

Next steps