Connect to a Firestore database

Use Firestore to set up a scalable NoSQL cloud database for your Cloud Run service. Firestore is a flexible, scalable, NoSQL database for mobile, web, and server development.

Using the Cloud Run integration described on this page, you can quickly connect your Cloud Run service to a new Firestore database.

Before you begin

  • Make sure the Cloud Run service you are integrating with is already deployed.
  • Review the Firestore pricing page. You are billed for individual resources used in the integration.

Required roles

To use the Cloud Run integrations, you or your administrator must grant IAM roles on two different principals.

Click to view required roles for your Google Account

To get the permissions that you need to use Cloud Run integrations, ask your administrator to grant your Google Account the following IAM roles on your project:

Click to view the required roles for the service account

To deploy the Cloud Run service, you can either use the auto-created Compute Engine default service account, or specify a user-managed service account. The service account must have the following roles:

Connect a service to a new Firestore database

Any configuration change leads to the creation of a new revision. Subsequent revisions will also automatically get this configuration setting unless you make explicit updates to change it.

You can connect a Cloud Run service to a Firestore database using the console or the command line.

Console

  1. In the Google Cloud console, go to the Cloud Run page.

    Go to Cloud Run

  2. Click the service in the services list that you want to use in this integration.

  3. Click the Integrations tab.

  4. Click Add integration.

  5. Click Firestore database.

  6. Use the default name or change the name to the value you want to use.

    image

  7. If prompted to enable a list of APIs, click Enable and wait for the APIs to be enabled.

  8. Under Resources, note the new resources that will be created as a result of this integration.

  9. Click Submit and wait for the integration and resources to be created. It can take up to 15 minutes.

Command line

  1. Update to the latest Google Cloud CLI:

    gcloud components update
    
  2. Create the integration:

    gcloud beta run integrations create \
    --type=firestore \
    --service=SERVICE \
    --region REGION
    

    Replace:

    • SERVICE with your Cloud Run service name.

    Optionally, include the --service-account=SERVICE_ACCOUNT_EMAIL flag.

    • SERVICE_ACCOUNT_EMAIL with the user-managed service account email address (PROJECT_NUMBER-compute@developer.gserviceaccount.com) that is used to deploy the service. Omit this flag if you want to use the default compute service account (SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com).

      To continue using the specified service account when deploying Cloud Run integrations, run the following command:

      gcloud config set runapps/deployment-service-account
      
  3. Wait up to 15 minutes, during which time a fully configured Firestore database is created and connected. In addition, a new Cloud Run revision is created, including environment variables that identify the database. When the process is complete, the following message is shown:

    [firestore] integration [firestore-xxx] has been updated successfully.
    
    To connect to the Firestore database, utilize the environment variable
    `FIRESTORE_DB_NAME`. This variable is added to the Cloud Run
    service for you.

    You can check the status by running gcloud beta run integrations describe.

View Firestore database integrations

To view the current status of Firestore database integrations for your Cloud Run service:

Console

  1. In the Google Cloud console, go to the Cloud Run page.

    Go to Cloud Run

  2. Click the service in the services list that you want to use in this integration.

  3. Click the Integrations tab.

  4. Locate the Firestore database integration you are interested in and click View details.

Command line

  1. Use the following command to get a list of available integrations:

    gcloud beta run integrations list
  2. Using a name from the returned list, display the details for it:

    gcloud beta run integrations describe INTEGRATION_NAME

    Replace INTEGRATION_NAME with the name of your Firestore database integration.

Delete Firestore database integrations

Deleting an integration will also delete all of the Google Cloud resources associated with that integration, but it will not delete your Cloud Run service.

To delete a Firestore database integration from your Cloud Run service:

Console

  1. In the Google Cloud console, go to the Cloud Run page.

    Go to Cloud Run

  2. Click the service you want to delete an integration from.

  3. Click the Integrations tab.

  4. Locate the Firestore database integration you are interested in and click the ellipsis icon to the right of the integration, then click Delete.

Command line

  1. Use the following command to get a list of available integrations:

    gcloud beta run integrations list
  2. Using a name from the returned list, delete the integration:

    gcloud beta run integrations delete INTEGRATION_NAME
    

    Replace:

    • INTEGRATION_NAME with the name of your Firestore database integration.

    Optionally, you can use the following flag options:

    Option Description
    --service-account The user-managed service account email address to perform the delete operation.

Access the Firestore database in your code

After you complete the integration, Cloud Run automatically adds the environment variable FIRESTORE_DB_NAME for use in your Cloud Run service code.

Sample code for services using Firestore

Refer to the Firestore documentation for Firestore Server library code samples or the following sample:

The Python sample in the following instructions requires a Firestore database created using the Cloud Run Integration, running in Native Firestore mode. You must also have an existing repository to push the code to.

  1. Create a directory for the sample files:

    mkdir SERVICE
    

    Replace SERVICE with your Cloud Run service name.

  2. Configure Docker authentication:

    gcloud auth configure-docker REGION-docker.pkg.dev
    

    Replace REGION with the Google Cloud region of the service.

  3. Create a requirements.txt file in your SERVICE directory, and add the following:

    flask
    google-cloud-firestore
    
  4. Create a Dockerfile file in your SERVICE directory, and add the following:

    FROM python:3.9-slim
    
    WORKDIR /app
    
    COPY requirements.txt ./
    RUN pip install -r requirements.txt
    
    COPY . .
    
    EXPOSE 8080
    
    CMD ["python", "app.py"]
    
  5. Create an app.py file in your SERVICE directory, and add the following:

    from flask import Flask, jsonify, request
    import google.cloud.firestore
    import os

    app = Flask(name) dbname = os.environ['FIRESTORE_DB_NAME'] db = google.cloud.firestore.Client(database=dbname) # Initialize Firestore client

    @app.route('/data', methods=['POST']) def add_data(): data = request.get_json() db.collection('city_person').add(data) return jsonify({'message': 'Data added successfully!'}), 201

    @app.route('/data', methods=['GET']) def get_data(): results = db.collection('city_person').stream() data_list = [doc.to_dict() for doc in results] return jsonify(data_list), 200

    if name == 'main': app.run(host='0.0.0.0', port=8080, debug=True)

  6. Navigate to your SERVICE directory:

    cd SERVICE
    

Replace SERVICE with the name of your Cloud Run service folder.

  1. Build the Docker image:

    docker build -t REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY_NAME/IMAGE_NAME:latest .
    

    Replace:

    • REGION with the Google Cloud region of the service.
    • PROJECT_ID with the Google Cloud project ID.
    • REPOSITORY_NAMEwith the name of the Artifact Registry repository.
    • IMAGE_NAME with a reference to the container image, for example, us-docker.pkg.dev/cloudrun/container/job:latest.
  2. Push the Docker image:

    docker push REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY_NAME/IMAGE_NAME:latest
    

    Replace:

    • REGION with the Google Cloud region of the service.
    • PROJECT_ID with the Google Cloud project ID.
    • REPOSITORY_NAMEwith the name of the Artifact Registry repository.
    • IMAGE_NAME with a reference to the container image, for example, us-docker.pkg.dev/cloudrun/container/job:latest.
  3. Deploy the service to Cloud Run:

    gcloud run deploy SERVICE_NAME --image REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY_NAME/IMAGE_NAME:latest --allow-unauthenticated --region REGION
    

Replace: REGIONwith the Google Cloud region of the service. PROJECT_ID with the Google Cloud project ID. REPOSITORY_NAMEwith the name of the Artifact Registry repository IMAGE_NAME with a reference to the container image, for example, us-docker.pkg.dev/cloudrun/container/job:latest.

After deployment is complete, the service URL is displayed next to the text URL.

  1. Configure the Firestore Integration for Cloud Run:

    gcloud beta run integrations create \
    --type=firestore \
    --service=SERVICE_NAME \
    --region REGION
    
  2. After deployment is complete, enter your service URL in the following read and write commands:

    1. Write data:

      curl -X POST SERVICE_URL/data -H "Content-Type: application/json" -d '{"name": "Alice", "city": "New York"}'
      
    2. Read data:

      curl https://SERVICE_URL/data
      

To see different results returned in the read data command, you can change the name and city in the write data command.

Limitations