---
title: "Container Service on Google Cloud"
description: "Deploy a container service on Google Cloud with Pulumi, Cloud Run, and Artifact Registry in TypeScript, Python, Go, C#, or HCL."
url: "https://www.pulumi.com/dev/templates/container-service/gcp/"
image: "https://www.pulumi.com/assets/og/dev/templates/container-service/gcp.png"
---

# Container Service on Google Cloud

Deploy a container service on Google Cloud with Pulumi, Cloud Run, and Artifact Registry in TypeScript, Python, Go, C#, or HCL.

The Google Cloud Container Service template scaffolds a Pulumi project that deploys a containerized service to [Google Cloud Run](https://www.pulumi.com/registry/packages/gcp/api-docs/cloudrun) for serverless container execution, with the container image stored in Artifact Registry. The template ships with placeholder app content so the project deploys end to end out of the box.

![An architecture diagram of the Google Cloud Container Service template](./architecture.svg)

## Before you begin

**TypeScript**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] A [Google Cloud account](https://cloud.google.com/free)
- [x] The [gcloud CLI](https://cloud.google.com/sdk/docs/install) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your Google Cloud credentials](https://www.pulumi.com/registry/packages/gcp/installation-configuration#credentials)
- [x] Permission to manage Cloud Run and Artifact Registry
- [x] A current version of [Node.js](https://nodejs.org/en/download) and [npm](https://www.npmjs.com/package/npm) installed locally
- [x] [Docker](https://docs.docker.com/get-started/get-docker/) installed and running

**Python**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] A [Google Cloud account](https://cloud.google.com/free)
- [x] The [gcloud CLI](https://cloud.google.com/sdk/docs/install) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your Google Cloud credentials](https://www.pulumi.com/registry/packages/gcp/installation-configuration#credentials)
- [x] Permission to manage Cloud Run and Artifact Registry
- [x] A current version of [Python](https://www.python.org/downloads/) and [pip](https://pip.pypa.io/en/stable/installation/), [Poetry](https://python-poetry.org/docs/) or [uv](https://docs.astral.sh/uv/getting-started/installation/) installed locally
- [x] [Docker](https://docs.docker.com/get-started/get-docker/) installed and running

**Go**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] A [Google Cloud account](https://cloud.google.com/free)
- [x] The [gcloud CLI](https://cloud.google.com/sdk/docs/install) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your Google Cloud credentials](https://www.pulumi.com/registry/packages/gcp/installation-configuration#credentials)
- [x] Permission to manage Cloud Run and Artifact Registry
- [x] A current version of [Go](https://go.dev/doc/install) installed locally
- [x] [Docker](https://docs.docker.com/get-started/get-docker/) installed and running

**C#**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] A [Google Cloud account](https://cloud.google.com/free)
- [x] The [gcloud CLI](https://cloud.google.com/sdk/docs/install) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your Google Cloud credentials](https://www.pulumi.com/registry/packages/gcp/installation-configuration#credentials)
- [x] Permission to manage Cloud Run and Artifact Registry
- [x] A current version of [.NET](https://dotnet.microsoft.com/en-us/download/dotnet) installed locally
- [x] [Docker](https://docs.docker.com/get-started/get-docker/) installed and running

**HCL**

For this walkthrough, you'll need:

- [x] A current version of the [Pulumi CLI](https://www.pulumi.com/docs/install/) ([Pulumi HCL](https://www.pulumi.com/docs/iac/languages-sdks/hcl/) requires no additional runtime)
- [x] A [Google Cloud account](https://cloud.google.com/free)
- [x] The [gcloud CLI](https://cloud.google.com/sdk/docs/install) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your Google Cloud credentials](https://www.pulumi.com/registry/packages/gcp/installation-configuration#credentials)
- [x] Permission to manage Cloud Run and Artifact Registry
- [x] [Docker](https://docs.docker.com/get-started/get-docker/) installed and running

## Create a new project

Create a new [project](https://www.pulumi.com/docs/iac/concepts/projects/) from the template:

**TypeScript**

```bash
mkdir my-container-service; cd my-container-service
pulumi new container-gcp-typescript
```

**Python**

```bash
mkdir my-container-service; cd my-container-service
pulumi new container-gcp-python
```

**Go**

```bash
mkdir my-container-service; cd my-container-service
pulumi new container-gcp-go
```

**C#**

```bash
mkdir my-container-service; cd my-container-service
pulumi new container-gcp-csharp
```

**HCL**

```bash
mkdir my-container-service; cd my-container-service
pulumi new container-gcp-hcl
```

The `pulumi new` command walks you through creating and configuring the new project and stack. A [stack](https://www.pulumi.com/docs/iac/concepts/stacks/) is an instance of a project, and you can have many of them (`dev`, `staging`, `prod`), each with its own [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.

This template's settings include:

**TypeScript / Python / Go / C#**

| Key | Description | Default |
| --- | --- | --- |
| `gcp:region` | The Google Cloud region to deploy into | `us-central1` |
| `gcp:project` | The Google Cloud project to deploy into | — |
| `appPath` | The path to the container application to deploy | `app` |
| `imageName` | The name to give the container image | `my-app` |
| `containerPort` | The port to expose on the container | `8080` |
| `cpu` | The number of virtual CPUs to allocate per container instance | `1` |
| `memory` | The amount of memory to allocate per container instance | `1Gi` |
| `concurrency` | The maximum number of concurrent requests to serve per container instance | `50` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set gcp:region <value>
pulumi config set gcp:project <value>
pulumi config set appPath <value>
pulumi config set imageName <value>
pulumi config set containerPort <value>
pulumi config set cpu <value>
pulumi config set memory <value>
pulumi config set concurrency <value>
```

**HCL**

| Key | Description | Default |
| --- | --- | --- |
| `gcp:project` | The Google Cloud project to deploy into | — |
| `region` | The Google Cloud region to deploy into | `us-central1` |
| `image_name` | The name to give the container image | `my-app` |
| `app_path` | The path to the container application to deploy | `./app` |
| `container_port` | The port to expose on the container | `8080` |
| `cpu` | The number of vCPUs to allocate per container instance | `1` |
| `memory` | The amount of memory to allocate per container instance | `1Gi` |
| `concurrency` | The maximum number of concurrent requests per container instance | `80` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set gcp:project <value>
pulumi config set region <value>
pulumi config set image_name <value>
pulumi config set app_path <value>
pulumi config set container_port <value>
pulumi config set cpu <value>
pulumi config set memory <value>
pulumi config set concurrency <value>
```

For `gcp:project`, enter the ID of an existing Google Cloud project. `gcloud config get-value project` prints the one gcloud is using. Press Enter at the others to keep the defaults.

## Review the code

**TypeScript / Python / Go / C# / HCL**

When setup completes, you'll see a few files:

- `Pulumi.yaml` contains the project name and the language it's written in.
- `Pulumi.dev.yaml` contains the `dev` stack's settings, including the values you just entered.
- `index.ts` contains the program code that declares your cloud resources.
- `app` holds a small web app that answers with a "Hello, world!" message, and the Dockerfile that builds it.

Take a moment to open them up and have a look. Here's what's in `index.ts`:

**TypeScript**

```typescript title="index.ts"
import * as pulumi from "@pulumi/pulumi";
import * as gcp from "@pulumi/gcp";
import * as dockerbuild from "@pulumi/docker-build";
import * as random from "@pulumi/random";

// Import the program's configuration settings.
const config = new pulumi.Config();
const imageName = config.get("imageName") || "my-app";
const appPath = config.get("appPath") || "./app";
const containerPort = config.getNumber("containerPort") || 8080;
const cpu = config.getNumber("cpu") || 1;
const memory = config.get("memory") || "1Gi";
const concurrency = config.getNumber("concurrency") || 50;

// Import the provider's configuration settings.
const gcpConfig = new pulumi.Config("gcp");
const location = gcpConfig.require("region");
const project = gcpConfig.require("project");

// Generate a unique Artifact Registry repository ID
const uniqueString = new random.RandomString("unique-string", {
    length: 4,
    lower: true,
    upper: false,
    numeric: true,
    special: false,
})
let repoId = uniqueString.result.apply(result => "repo-" + result);

// Create an Artifact Registry repository
const repository = new gcp.artifactregistry.Repository("repository", {
    description: "Repository for container image",
    format: "DOCKER",
    location: location,
    repositoryId: repoId,
});

// Form the repository URL
let repoUrl = pulumi.concat(location, "-docker.pkg.dev/", project, "/", repository.repositoryId);

// Create a container image for the service.
// Before running `pulumi up`, configure Docker for authentication to Artifact Registry
// as described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
const image = new dockerbuild.Image("image", {
    tags: [pulumi.concat(repoUrl, "/", imageName)],
    context: {
        location: appPath,
    },
    // Cloud Run currently requires x86_64 images
    // https://cloud.google.com/run/docs/container-contract#languages
    platforms: ["linux/amd64"],
    push: true,
});

// Create a Cloud Run service definition.
const service = new gcp.cloudrun.Service("service", {
    location,
    template: {
        spec: {
            containers: [
                {
                    image: image.ref,
                    resources: {
                        limits: {
                            memory,
                            cpu: cpu.toString(),
                        },
                    },
                    ports: [
                        {
                            containerPort,
                        },
                    ],
                }
            ],
            containerConcurrency: concurrency,
        },
    },
});

// Create an IAM member to allow the service to be publicly accessible.
const invoker = new gcp.cloudrun.IamMember("invoker", {
    location,
    service: service.name,
    role: "roles/run.invoker",
    member: "allUsers",
});

// Export the URL of the service.
export const url = service.statuses.apply(statuses => statuses[0]?.url);
```

**Python**

```python title="__main__.py"
import pulumi
import pulumi_docker_build as docker_build
from pulumi_gcp import artifactregistry, cloudrun
import pulumi_random as random

# Import the program's configuration settings.
config = pulumi.Config()
app_path = config.get("appPath", "./app")
image_name = config.get("imageName", "my-app")
container_port = config.get_int("containerPort", 8080)
cpu = config.get_int("cpu", 1)
memory = config.get("memory", "1Gi")
concurrency = config.get_int("concurrency", 50)

# Import the provider's configuration settings.
gcp_config = pulumi.Config("gcp")
location = gcp_config.require("region")
project = gcp_config.require("project")

# Create a unique Artifact Registry repository ID
unique_string = random.RandomString(
    "unique-string",
    length=4,
    lower=True,
    upper=False,
    numeric=True,
    special=False,
)
repo_id = pulumi.Output.concat(
    "repo-",
    unique_string.result
)

# Create an Artifact Registry repository
repository = artifactregistry.Repository(
    "repository",
    description="Repository for container image",
    format="DOCKER",
    location=location,
    repository_id=repo_id,
)

# Form the repository URL
repo_url = pulumi.Output.concat(
    location,
    "-docker.pkg.dev/",
    project,
    "/",
    repository.repository_id
)

# Create a container image for the service.
# Before running `pulumi up`, configure Docker for Artifact Registry authentication
# as described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
image = docker_build.Image(
    "image",
    tags=[pulumi.Output.concat(repo_url, "/", image_name)],
    context=docker_build.BuildContextArgs(
        location=app_path,
    ),
    # Cloud Run currently requires x86_64 images
    # https://cloud.google.com/run/docs/container-contract#languages
    platforms=[docker_build.Platform.LINUX_AMD64],
    push=True,
)

# Create a Cloud Run service definition.
service = cloudrun.Service(
    "service",
    location=location,
    template={
        "spec": {
            "containers": [
                {
                    "image": image.ref,
                    "resources": {
                        "limits": {
                            "memory": memory,
                            "cpu": str(cpu),
                        },
                    },
                    "ports": [
                        {
                            "container_port": container_port,
                        },
                    ],
                    "envs": [
                        {
                            "name": "FLASK_RUN_PORT",
                            "value": str(container_port),
                        },
                    ],
                },
            ],
            "container_concurrency": concurrency,
        },
    },
)

# Create an IAM member to make the service publicly accessible.
invoker = cloudrun.IamMember(
    "invoker",
    location=location,
    service=service.name,
    role="roles/run.invoker",
    member="allUsers",
)

# Export the URL of the service.
pulumi.export("url", service.statuses.apply(lambda statuses: statuses[0].url))
```

**Go**

```go title="main.go"
package main

import (
	"strconv"

	"github.com/pulumi/pulumi-docker-build/sdk/go/dockerbuild"
	"github.com/pulumi/pulumi-gcp/sdk/v10/go/gcp/artifactregistry"
	"github.com/pulumi/pulumi-gcp/sdk/v10/go/gcp/cloudrun"
	"github.com/pulumi/pulumi-random/sdk/v4/go/random"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {

		// Import the program's configuration settings.
		cfg := config.New(ctx, "")
		appPath := "./app"
		if param := cfg.Get("appPath"); param != "" {
			appPath = param
		}
		imageName := "my-app"
		if param := cfg.Get("imageName"); param != "" {
			imageName = param
		}
		containerPort := 8080
		if param := cfg.GetInt("containerPort"); param != 0 {
			containerPort = param
		}
		cpu := 1
		if param := cfg.GetInt("cpu"); param != 0 {
			cpu = param
		}
		memory := "1Gi"
		if param := cfg.Get("memory"); param != "" {
			memory = param
		}
		concurrency := 50
		if param := cfg.GetInt("concurrency"); param != 0 {
			concurrency = param
		}

		// Import the provider's configuration settings.
		providerConfig := config.New(ctx, "gcp")
		location := providerConfig.Require("region")
		project := providerConfig.Require("project")

		// Generate a unique Artifact Registry repository ID
		uniqueString, err := random.NewRandomString(ctx, "unique-string", &random.RandomStringArgs{
			Length:  pulumi.Int(4),
			Lower:   pulumi.Bool(true),
			Upper:   pulumi.Bool(false),
			Numeric: pulumi.Bool(true),
			Special: pulumi.Bool(false),
		})
		if err != nil {
			return err
		}
		repoId := pulumi.Sprintf("repo-%s", uniqueString.Result)

		// Create an Artifact Registry repository
		repository, err := artifactregistry.NewRepository(ctx, "repository", &artifactregistry.RepositoryArgs{
			Description:  pulumi.String("Repository for container image"),
			Format:       pulumi.String("DOCKER"),
			Location:     pulumi.String(location),
			RepositoryId: repoId,
		})
		if err != nil {
			return err
		}

		// Form the repository URL
		repoUrl := pulumi.Sprintf("%s-docker.pkg.dev/%s/%s", repository.Location, project, repository.RepositoryId)

		// Create a container image for the service.
		// Before running `pulumi up`, configure Docker for authentication to Artifact Registry as
		// described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
		image, err := dockerbuild.NewImage(ctx, "image", &dockerbuild.ImageArgs{
			Tags: pulumi.StringArray{pulumi.Sprintf("%s/%s", repoUrl, imageName)},
			Context: &dockerbuild.BuildContextArgs{
				Location: pulumi.String(appPath),
			},
			// Cloud Run currently requires x86_64 images
			// https://cloud.google.com/run/docs/container-contract#languages
			Platforms: dockerbuild.PlatformArray{"linux/amd64"},
			Push:      pulumi.Bool(true),
		})
		if err != nil {
			return err
		}

		// Create a Cloud Run service definition.
		service, err := cloudrun.NewService(ctx, "service", &cloudrun.ServiceArgs{
			Location: pulumi.String(location),
			Template: cloudrun.ServiceTemplateArgs{
				Spec: cloudrun.ServiceTemplateSpecArgs{
					Containers: cloudrun.ServiceTemplateSpecContainerArray{
						cloudrun.ServiceTemplateSpecContainerArgs{
							Image: image.Ref,
							Resources: cloudrun.ServiceTemplateSpecContainerResourcesArgs{
								Limits: pulumi.ToStringMap(map[string]string{
									"memory": memory,
									"cpu":    strconv.Itoa(cpu),
								}),
							},
							Ports: cloudrun.ServiceTemplateSpecContainerPortArray{
								cloudrun.ServiceTemplateSpecContainerPortArgs{
									ContainerPort: pulumi.Int(containerPort),
								},
							},
						},
					},
					ContainerConcurrency: pulumi.Int(concurrency),
				},
			},
		})
		if err != nil {
			return err
		}

		// Create an IAM member to make the service publicly accessible.
		_, err = cloudrun.NewIamMember(ctx, "invoker", &cloudrun.IamMemberArgs{
			Service:  service.Name,
			Location: pulumi.String(location),
			Role:     pulumi.String("roles/run.invoker"),
			Member:   pulumi.String("allUsers"),
		})
		if err != nil {
			return err
		}

		// Export the URL of the service.
		ctx.Export("url", service.Statuses.Index(pulumi.Int(0)).Url())

		return nil
	})
}
```

**C#**

```csharp title="Program.cs"
using Pulumi;
using Gcp = Pulumi.Gcp;
using DockerBuild = Pulumi.DockerBuild;
using System.Collections.Generic;
using Random = Pulumi.Random;
using Output = Pulumi.Output;

return await Deployment.RunAsync(() =>
{
    // Import the program's configuration settings.
    var config = new Config();
    var appPath = config.Get("appPath") ?? "./app";
    var imageName = config.Get("imageName") ?? "my-app";
    var containerPort = config.GetInt32("containerPort") ?? 8080;
    var cpu = config.GetInt32("cpu") ?? 1;
    var memory = config.Get("memory") ?? "1Gi";
    var concurrency = config.GetInt32("concurrency") ?? 50;

    // Import the provider's configuration settings.
    var gcpConfig = new Config("gcp");
    var location = gcpConfig.Require("region");
    var project = gcpConfig.Require("project");

    // Generate a unique Artifact Registry repository ID
    var uniqueString = new Random.RandomString("unique-string", new()
    {
        Length = 4,
        Lower = true,
        Upper = false,
        Numeric = true,
        Special = false,
    });
    var repoId = Output.Format($"repo-{uniqueString.Result}");

    // Create an Artifact Registry repository
    var repository = new Gcp.ArtifactRegistry.Repository("repository", new()
    {
        Description = "Repository for container image",
        Format = "DOCKER",
        Location = location,
        RepositoryId = repoId,
    });

    // Form the repository URL
    var repoUrl = Output.Format($"{location}-docker.pkg.dev/{project}/{repository.RepositoryId}");

    // Create a container image for the service.
    // Before running `pulumi up`, configure Docker for Artifact Registry authentication
    // as described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
    var image = new DockerBuild.Image("image", new()
    {
        Tags = new[]
        {
            Output.Format($"{repoUrl}/{imageName}"),
        },
        Context = new DockerBuild.Inputs.BuildContextArgs
        {
            Location = appPath,
        },
        Platforms = new[]
        {
            // Cloud Run currently requires x86_64 images
            // https://cloud.google.com/run/docs/container-contract#languages
            DockerBuild.Platform.Linux_amd64,
        },
        Push = true,
    });

    // Create a Cloud Run service definition.
    var service = new Gcp.CloudRun.Service("service", new Gcp.CloudRun.ServiceArgs
    {
        Location = location!,
        Template = new Gcp.CloudRun.Inputs.ServiceTemplateArgs
        {
            Spec = new Gcp.CloudRun.Inputs.ServiceTemplateSpecArgs
            {
                Containers = new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerArgs[]
                {
                    new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerArgs
                    {
                        Image = image.Ref,
                        Resources = new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerResourcesArgs
                        {
                            Limits = {
                                { "memory", memory },
                                { "cpu", cpu.ToString() },
                            },
                        },
                        Ports = new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerPortArgs[]
                        {
                            new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerPortArgs
                            {
                                ContainerPort = containerPort,
                            },
                        },
                        Envs = new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerEnvArgs[]
                        {
                            new Gcp.CloudRun.Inputs.ServiceTemplateSpecContainerEnvArgs
                            {
                                Name = "ASPNETCORE_URLS",
                                Value = $"http://*:{containerPort}",
                            },
                        },
                    },
                },
                ContainerConcurrency = concurrency,
            },
        },
    });

    // Create an IAM member to make the service publicly accessible.
    var invoker = new Gcp.CloudRun.IamMember("invoker", new Gcp.CloudRun.IamMemberArgs
    {
        Location = location!,
        Service = service.Name,
        Role = "roles/run.invoker",
        Member = "allUsers",
    });

    // Export the URL of the service.
    return new Dictionary<string, object?>
    {
        ["url"] = service.Statuses.Apply(statuses => statuses[0]?.Url),
    };
});
```

**HCL**

```hcl title="main.tf"
terraform {
  required_providers {
    gcp = {
      source = "pulumi/gcp"
    }
    docker-build = {
      source = "pulumi/docker-build"
    }
    random = {
      source = "pulumi/random"
    }
  }
}

variable "region" {
  description = "The Google Cloud region to deploy into"
  type        = string
  default     = "us-central1"
}

variable "image_name" {
  description = "The name to give the container image"
  type        = string
  default     = "my-app"
}

variable "app_path" {
  description = "The path to the container application to deploy"
  type        = string
  default     = "./app"
}

variable "container_port" {
  description = "The port to expose on the container"
  type        = number
  default     = 8080
}

variable "cpu" {
  description = "The number of vCPUs to allocate per container instance"
  type        = number
  default     = 1
}

variable "memory" {
  description = "The amount of memory to allocate per container instance"
  type        = string
  default     = "1Gi"
}

variable "concurrency" {
  description = "The maximum number of concurrent requests per container instance"
  type        = number
  default     = 80
}

# Import the provider's configuration settings.
data "gcp_organizations_client_config" "current" {}

# Form the repository URL
locals {
  repo_url = "${var.region}-docker.pkg.dev/${data.gcp_organizations_client_config.current.project}/${gcp_artifactregistry_repository.repository.repository_id}"
}

# Generate a unique Artifact Registry repository ID
resource "random_random_string" "unique-string" {
  length  = 4
  lower   = true
  upper   = false
  numeric = true
  special = false
}

# Create an Artifact Registry repository
resource "gcp_artifactregistry_repository" "repository" {
  description   = "Repository for the container image"
  format        = "DOCKER"
  location      = var.region
  repository_id = "repo-${random_random_string.unique-string.result}"
}

# Create a container image for the service.
# Before running `pulumi up`, configure Docker for authentication to Artifact Registry
# as described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
resource "docker-build_image" "image" {
  tags      = ["${local.repo_url}/${var.image_name}"]
  platforms = ["linux/amd64"]
  push      = true

  context = {
    location = var.app_path
  }
}

# Create a Cloud Run service definition.
resource "gcp_cloudrun_service" "service" {
  location = var.region

  template = {
    spec = {
      container_concurrency = var.concurrency
      containers = [{
        image = docker-build_image.image.ref
        ports = [{
          container_port = var.container_port
        }]
        resources = {
          limits = {
            cpu    = tostring(var.cpu)
            memory = var.memory
          }
        }
      }]
    }
  }
}

# Create an IAM member to allow the service to be publicly accessible.
resource "gcp_cloudrun_iam_member" "invoker" {
  location = var.region
  service  = gcp_cloudrun_service.service.name
  role     = "roles/run.invoker"
  member   = "allUsers"
}

# Export the URL of the service.
output "url" {
  value = gcp_cloudrun_service.service.statuses[0].url
}
```

## Deploy the project

Before the first deploy, sign in the gcloud CLI, turn on the Cloud Run and Artifact Registry APIs in your project, and let Docker push images to Artifact Registry in your region. Pulumi uses your application default credentials, but these commands, and Docker's push, use the gcloud CLI's own sign-in:

**TypeScript / Python / Go / C#**

```bash
$ gcloud auth login
$ gcloud services enable run.googleapis.com artifactregistry.googleapis.com --project $(pulumi config get gcp:project)
$ gcloud auth configure-docker "$(pulumi config get gcp:region)-docker.pkg.dev"
```

**HCL**

```bash
$ gcloud auth login
$ gcloud services enable run.googleapis.com artifactregistry.googleapis.com --project $(pulumi config get gcp:project)
$ gcloud auth configure-docker "$(pulumi config get region)-docker.pkg.dev"
```

Then deploy with [`pulumi up`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_up). It starts with a preview of what it's about to create and asks before it changes anything. Choose `yes` to deploy. Pulumi builds the container image with Docker on your machine, so Docker needs to be running.

```bash
$ pulumi up
```

Pulumi adds a random suffix to most resource names, so the Cloud Run service `service` becomes something like `service-4f8a2c1`. This is [autonaming](https://www.pulumi.com/docs/iac/concepts/resources/names/#autonaming). It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.

When it finishes, Pulumi prints the stack's [outputs](https://www.pulumi.com/docs/iac/concepts/stacks/#outputs), values it only knows once the resources exist:

**`url`**

The HTTPS URL of your Cloud Run service.

Read one any time with `pulumi stack output <name>`, or pass it to another command. This opens the service in your browser:

**macOS**

```bash
$ open $(pulumi stack output url)
```

**Linux**

```bash
$ xdg-open $(pulumi stack output url)
```

**Windows**

```powershell
> Start-Process (pulumi stack output url)
```

To check it from the terminal, call the service with `curl`:

**Linux / macOS**

```bash
$ curl $(pulumi stack output url)
{"message":"Hello, world!"}
```

**Windows**

```powershell
> curl.exe (pulumi stack output url)
{"message":"Hello, world!"}
```

**Need help?**

If `pulumi up` reports `failed to load application credentials`, sign in again:

```bash
$ gcloud auth application-default login
```

Still stuck? [Let us know](https://github.com/pulumi/docs/issues/new).

## Customize the project

Projects created with this template expose the following [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings:

**TypeScript / Python / Go / C#**

**`containerPort`**

The port mapping for the container service. Defaults to port `8080`.

**`cpu`**

The amount of CPU to allocate to each container instance. Defaults to `1` CPU.

**`memory`**

The amount of memory to allocate to each container instance. Defaults to `1Gi`.

**`concurrency`**

The maximum number of concurrent requests per container instance. Defaults to `50`.

**`imageName`**

The name of the container image deployed to your Cloud Run service. Defaults to `my-app`.

**`appPath`**

The location of the Dockerfile used to build the container image. Defaults to the `app` folder, which contains a "Hello World" example app.

**HCL**

**`region`**

The Google Cloud region to deploy into. Defaults to `us-central1`.

**`image_name`**

The name of the container image deployed to your Cloud Run service. Defaults to `my-app`.

**`app_path`**

The location of the Dockerfile used to build the container image. Defaults to the `app` folder, which contains a "Hello World" example app.

**`container_port`**

The port mapping for the container service. Defaults to port `8080`.

**`cpu`**

The amount of CPU to allocate to each container instance. Defaults to `1` CPU.

**`memory`**

The amount of memory to allocate to each container instance. Defaults to `1Gi`.

**`concurrency`**

The maximum number of concurrent requests per container instance. Defaults to `80`.

All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, `Pulumi.dev.yaml`) or by changing their values with [`pulumi config set`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_config_set).

For example, move the app to port 3000, then list the project's Cloud Run services with their container port to check that yours now shows `3000`:

**TypeScript / Python / Go / C#**

**Linux / macOS**

```bash
$ pulumi config set containerPort 3000
$ pulumi up
$ gcloud run services list --project $(pulumi config get gcp:project) --region $(pulumi config get gcp:region) \
    --format="table(metadata.name, spec.template.spec.containers[0].ports[0].containerPort)"
```

**Windows**

```powershell
> pulumi config set containerPort 3000
> pulumi up
> gcloud run services list --project (pulumi config get gcp:project) --region (pulumi config get gcp:region) `
    --format="table(metadata.name, spec.template.spec.containers[0].ports[0].containerPort)"
```

**HCL**

**Linux / macOS**

```bash
$ pulumi config set container_port 3000
$ pulumi up
$ gcloud run services list --project $(pulumi config get gcp:project) --region $(pulumi config get region) \
    --format="table(metadata.name, spec.template.spec.containers[0].ports[0].containerPort)"
```

**Windows**

```powershell
> pulumi config set container_port 3000
> pulumi up
> gcloud run services list --project (pulumi config get gcp:project) --region (pulumi config get region) `
    --format="table(metadata.name, spec.template.spec.containers[0].ports[0].containerPort)"
```

The app picks up the new port too, so the `curl` command above still gets the same "Hello, world!" reply.

To see what else you can add, browse the [Google Cloud provider](https://www.pulumi.com/registry/packages/gcp/) in the Pulumi Registry.

## Cleaning up

You can cleanly destroy the stack and all of its infrastructure with [`pulumi destroy`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_destroy):

```bash
$ pulumi destroy
```

## Learn more

- Browse other architecture templates in the [Templates gallery](https://www.pulumi.com/templates).
- Explore the [Google Cloud provider API docs](https://www.pulumi.com/registry/packages/gcp) in the Pulumi Registry.
- Walk through Pulumi from the ground up in [Pulumi Tutorials](https://www.pulumi.com/dev/browse/?type=tutorial).
- Read the latest [container posts on the Pulumi blog](https://www.pulumi.com/blog/tag/containers).
