Build and create a Node.js job in Cloud Run

Learn how to create a simple Cloud Run job, then deploy from source, which automatically packages your code into a container image, uploads the container image to Artifact Registry, and then deploys to Cloud Run. You can use other languages in addition to the ones shown.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  7. Verify that billing is enabled for your Google Cloud project.

  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  13. Verify that billing is enabled for your Google Cloud project.

  14. Enable the Cloud Run Admin API and Cloud Build APIs:

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    gcloud services enable run.googleapis.com cloudbuild.googleapis.com

    After the Cloud Run Admin API is enabled, the Compute Engine default service account is automatically created.

  15. Review Cloud Run pricing or estimate costs with the pricing calculator.

Required roles

To get the permissions that you need to complete this quickstart, ask your administrator to grant you the following IAM roles:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Grant the Cloud Build service account access to your project

Cloud Build automatically uses the Compute Engine default service account as the default Cloud Build service account to build your source code and Cloud Run resource, unless you override this behavior.

For Cloud Build to build your sources, grant the Cloud Build service account the Cloud Run Builder (roles/run.builder) role on your project:

gcloud projects add-iam-policy-binding PROJECT_ID \
    --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \
    --role=roles/run.builder

Replace PROJECT_ID with your Google Cloud project ID and SERVICE_ACCOUNT_EMAIL_ADDRESS with the email address of the Cloud Build service account. If you're using the Compute Engine default service account as the Cloud Build service account, then use the following format for the service account email address:

PROJECT_NUMBER-compute@developer.gserviceaccount.com

Replace PROJECT_NUMBER with your Google Cloud project number.

For detailed instructions on how to find your project ID, and project number, see Creating and managing projects.

Granting the Cloud Run builder role takes a couple of minutes to propagate.

Writing the sample job

To write a job in Node.js:

  1. Create a new directory named jobs and change directory into it:

    mkdir jobs
    cd jobs
    
  2. Create a package.json file with the following contents:

    {
        "name": "jobs",
        "version": "1.0.0",
        "description": "Node.js sample for Cloud Run jobs",
        "main": "index.js",
        "scripts": {
            "start": "node index.js"
        },
        "engines": {
            "node": ">=16.0.0"
        },
        "author": "Google LLC",
        "license": "Apache-2.0"
    }
    
  3. In the same directory, create a index.js file for the actual job code. Copy the following sample lines into it:

    // Retrieve Job-defined env vars
    const {CLOUD_RUN_TASK_INDEX = 0, CLOUD_RUN_TASK_ATTEMPT = 0} = process.env;
    // Retrieve User-defined env vars
    const {SLEEP_MS, FAIL_RATE} = process.env;
    
    // Define main script
    const main = async () => {
      console.log(
        `Starting Task #${CLOUD_RUN_TASK_INDEX}, Attempt #${CLOUD_RUN_TASK_ATTEMPT}...`
      );
      // Simulate work
      if (SLEEP_MS) {
        await sleep(SLEEP_MS);
      }
      // Simulate errors
      if (FAIL_RATE) {
        try {
          randomFailure(FAIL_RATE);
        } catch (err) {
          err.message = `Task #${CLOUD_RUN_TASK_INDEX}, Attempt #${CLOUD_RUN_TASK_ATTEMPT} failed.\n\n${err.message}`;
          throw err;
        }
      }
      console.log(`Completed Task #${CLOUD_RUN_TASK_INDEX}.`);
    };
    
    // Wait for a specific amount of time
    const sleep = ms => {