☁️Static Pages Hosting by Cloud Run

The static site hosting example by Cloud Run and the custom domain setting

Overview 

Prerequisites 

How to Build the Static Page Site 

1. Enable API 

To use the Cloud DNS service and manage the resource by the Tofu or Terraform or something, a developer need to enable the Cloud DNS service.

 1// Variable for GCP
 2variable "gcp_project" {
 3  type = object({
 4    project     = string   // The gcp project name
 5    region      = string   // The region of gcp project
 6  })
 7}
 8
 9variable "gcp_services" {
10  type = list(string)      // Enabling the service name of api
11}
12
13// Enable APIs
14resource "google_project_service" "api_enable" {
15  for_each = toset(var.gcp_services)
16  project  = var.gcp_project.project
17  service  = each.value
18}

2. Prepare the static pages container 

In this part, to build simple file http server, this part share golang example code. You can choose any language or a web server container for this.

 1package main
 2
 3import (
 4	"embed"
 5	"flag"
 6	"fmt"
 7	"io/fs"
 8	"log"
 9	"net/http"
10	"os"
11)
12
13//go:embed pub
14var staticFs embed.FS
15
16func fileHandler() http.HandlerFunc {
17	pub, _ := fs.Sub(staticFs, "pub")
18	handler := http.FileServerFS(pub)
19
20	return func(w http.ResponseWriter, req *http.Request) {
21		w.Header().Set("Cache-Control", "public, max-age=3600")
22		handler.ServeHTTP(w, req)
23	}
24}
25
26func main() {
27	portNum := flag.String("p", "8080", "server port")
28	host := flag.String("i", "", "interface name")
29	flag.Parse()
30
31	portEnv := os.Getenv("PORT")
32	if len(portEnv) > 0 {
33		*portNum = portEnv
34	}
35
36	srv := fmt.Sprintf("%s:%s", *host, *portNum)
37	log.Printf("server: %s", srv)
38
39	handler := fileHandler()
40	http.Handle("/", handler)
41
42	if err := http.ListenAndServe(srv, nil); err != nil {
43		log.Fatal(err)
44	}
45}

The below command is the bhild check on local

1go build -o chk ./cmd/main.go

3. Set up the Artifact Registry 

To run the file server on Cloud Run, the Artifact Registry is required. to store the file server container, this part builds the Artifact Registry.

4. Build the Cloud Run 

To run the file server container, this part builds the Cloud Run Service.

5. Set up a Custom domain 

To allow domain name access, this part set up custom domain configuration.


SEE ALSO 

GCP   StaticPages  

memoes / Gcp / Static Pages Hosting by Cloud Run

日本最大級ショッピングサイト!お買い物なら楽天市場