Home Backend Development Golang How to Deploy a Go service to GCP Cloud Run

How to Deploy a Go service to GCP Cloud Run

Oct 03, 2024 am 06:14 AM

How to Deploy a Go service to GCP Cloud Run

Deploying a Go service to GCP Cloud Run involves several steps, including setting up a Dockerfile and configuring environment variables. 

This guide will walk you through the process.

Set up your GCP Project

Start off by going to GCP create account if havent done so yet.

  1. Create a GCP Project.
  • Go to the GCP console and create a new project.

  • Note the project ID for deployment.

How to Deploy a Go service to GCP Cloud Run

  1. Enable required APIs.
  • Enable the Cloud Run API and Container Registry API.
  1. Install Google Cloud SDK
  • Initialize your repository with gcloud init.

Create your Go Service

Ensure your Go app can run locally and set up a Dockerfile.

cmd/main.go

// cmd/main.go
func main() {
 flag.Parse()

 a := app.Application{}

 if err := a.LoadConfigurations(); err != nil {
        log.Fatalf("Failed to load configurations: %v", err)
    }

    if err := runtime.Start(&a); err != nil {
        log.Fatalf("Failed to start the application: %v", err)
    }

}
Copy after login

runtime/base.go

func Start(a *app.Application) error {
    router := gin.New()

    router.Use(cors.New(md.CORSMiddleware()))

    api.SetCache(router, a.RedisClient)
    api.SetRoutes(router, a.FireClient, a.FireAuth, a.RedisClient)

    err := router.Run(":" + a.ListenPort)
    log.Printf("Starting server on port: %s", a.ListenPort)
    if err != nil {
        return err
    }

    return nil
}
Copy after login

Create Dockerfile

# Use the official Go image as the base image
FROM golang:1.18

WORKDIR /app

# Copy the Go module files
COPY go.mod go.sum ./

RUN go mod download

# Copy the rest of the application code
COPY . .

RUN go build -o main  ./cmd/main.go

CMD ["./main"]
Copy after login

Set Up Env variables

Use shell script to automate setting env variables for GCP 

as env-variables.sh.

// env-variables.sh
#!/bin/bash

# Environment variables
export PROJECT_ID=recepies-6e7c0
export REGION=europe-west1

export REDIS_URL="rediss://default:AVrvA....-lemur-23279.u....:6379"
export FIREBASE_ACCOUNT_KEY="/app/config/account_key.json"
export CLIENT_URL="https://.....vercel.app/"
Copy after login

Deployment script as deploy-with-yaml.sh.

#!/bin/bash

source env-variables.sh

#Comment if correctly deployed
docker build -t gcr.io/$PROJECT_ID/recipe-server:latest .
docker push gcr.io/$PROJECT_ID/recipe-server:latest

#Uncomment if json needs to be added to GCP 
# gcloud secrets create firebase-account-key --data-file=/mnt/c/own_dev/RecipesApp/server/config/account_key.json --project=recepies-6e7c0

#Add permission IAM
gcloud projects add-iam-policy-binding recepies-6e7c0 \
    --member="serviceAccount:service-988443547488@serverless-robot-prod.iam.gserviceaccount.com" \
    --role="roles/artifactregistry.reader"

gcloud run deploy recipe-service \
  --image gcr.io/$PROJECT_ID/recipe-server:latest \
  --region $REGION \
  --platform managed \
  --set-env-vars REDIS_URL=$REDIS_URL,CLIENT_URL=$CLIENT_URL,FIREBASE_ACCOUNT_KEY=$FIREBASE_ACCOUNT_KEY
Copy after login

Deployment to your GCP Cloud Run

Run the deployment script

env-variables.sh

Common Issues and Troubleshooting

  • Permission Issues: Ensure the Cloud Run Service Agent has permission to read the image.
  • Environment Variables: Verify that all required environment variables are set correctly.
  • Port Configuration: Ensure the PORT environment variable is set correctly.

How to Deploy a Go service to GCP Cloud Run

When all set up as needed you will see Image being build and pushed to your GCP project Artifact Registry. In the end i got this.

a9099c3159f5: Layer already exists
latest: digest: sha256:8c98063cd5b383df0b444c5747bb729ffd17014d42b049526b8760a4b09e5df1 size: 2846
Deploying container to Cloud Run service [recipe-service] in project [recepies-6e7c0] region [europe-west1]
✓ Deploying... Done.
  ✓ Creating Revision...
  ✓ Routing traffic...
Done.
Service [recipe-service] revision [recipe-service-00024-5mh] has been deployed and is serving 100 percent of traffic.
Service URL: https://recipe-service-819621241045.europe-west1.run.app
Copy after login

There is a standart error that I came across multiple times ?

Deploying container to Cloud Run service [recipe-service] in project [recepies-6e7c0] region [europe-west1] X Deploying… - Creating Revision… . Routing traffic… Deployment failed ERROR: 
(gcloud.run.deploy) Revision 'recipe-service-00005-b6h' 
is not ready and cannot serve traffic. Google Cloud Run Service Agent service-819621241045@serverless-robot-prod.iam.gserviceaccount.com must have permission to read the image, 
gcr.io/loyal-venture-436807-p7/recipe-server:latest. Ensure that the provided container image URL is correct and that the above account has permission to access the image. If you just enabled the Cloud Run API, the permissions might take a few minutes to propagate. Note that the image is from project [loyal-venture-436807-p7], which is not the same as this project [recepies-6e7c0]. Permission must be granted to the Google Cloud Run Service 
Agent service-819621241045@serverless-robot-prod.iam.gserviceaccount.com from this project. See https://cloud.google.com/run/docs/deploying#other-projects
Copy after login

Often it states that PORT=8080 could not be set but main issue is something else like env variable not set or in my case firebase account_key.json incorrectly set for deployment.


When all is set you can test the connection and do requests.

I have my frontend deployed in Vercel and bellow you can see my Cloud Run Logs

How to Deploy a Go service to GCP Cloud Run

Deploying a Go service to GCP Cloud Run can be streamlined with a few key configurations and automation scripts. 

Although there might be some common errors, such as permission issues or incorrect environment variables, understanding how to troubleshoot them through Cloud Run logs ensures a smooth deployment.
My repo you can find here.

The above is the detailed content of How to Deploy a Go service to GCP Cloud Run. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

See all articles