Closed3

tiltでgolangのホットリロード

not75743not75743

k8s

ディレクトリ構成

.
|-- Tiltfile
|-- build # tilt up時にbuildしたイメージが格納される
|   `-- test-go
|-- deployments
|   |-- Dockerfile
|   `-- deployments.yaml
|-- go.mod
`-- main.go

tiltfile

# -*- mode: Python -*-
load('ext://restart_process', 'docker_build_with_restart')

# Goのビルドをホストマシン上で行うlocal_resourceの追加
local_resource(
    'test-go-compile',
    'go build -o build/test-go ./',
    deps=['./main.go', './go.mod'],
)

# Dockerビルド設定
docker_build_with_restart(
    'test-go-image', 
    '.', 
    entrypoint=['/app/test-go'],
    dockerfile='deployments/Dockerfile', 
    only=[
        './build',
    ],
    live_update=[
        sync('./build', '/app'),  # ビルドされたバイナリを /appに同期
    ],
)

# Kubernetesマニフェストの読み込み
k8s_yaml('deployments/deployments.yaml')

# Kubernetesリソースの定義とポートフォワードの設定
k8s_resource('test-go', port_forwards=8080, resource_deps=['test-go-compile'])

main.go

package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World")
}

func main() {
	http.HandleFunc("/", handler) // ルートパスに対してハンドラーを設定
	fmt.Println("Starting server on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Server failed:", err)
	}
}

Dockerfile

FROM debian:bookworm-slim
WORKDIR /app
ADD ./build .
ENTRYPOINT test-go

deployments.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-go
  labels:
    app: test-go
spec:
  replicas: 1  # レプリカ数を明示的に設定
  selector:
    matchLabels:
      app: test-go
  template:
    metadata:
      labels:
        app: test-go
    spec:
      containers:
      - name: test-go
        image: test-go-image
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: test-go-service
  labels:
    app: test-go
spec:
  selector:
    app: test-go
  type: NodePort
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30080
not75743not75743

ホットリロード

func handler(w http.ResponseWriter, r *http.Request) {
-	fmt.Fprintf(w, "Hello, World")
+	fmt.Fprintf(w, "Hello, World v2")
}

tiltログ

test-go-comp… │ 
test-go-comp… │ 1 File Changed: [main.go]
test-go-comp… │ Running cmd: go build -o build/test-go ./
      test-go │ 
      test-go │ 1 File Changed: [build/test-go]
      test-go │ Will copy 1 file(s) to container: [test-go-8455fd9c64-l6sgk/test-go]
      test-go │ - '/workspace/tilt-test/build/test-go' --> '/app/test-go'
      test-go │ [CMD 1/1] sh -c date > /tmp/.restart-proc
      test-go │   → Container test-go-8455fd9c64-l6sgk/test-go updated!
      test-go │ Starting server on :8080


1秒ほど

確認

$ curl localhost:30080
Hello, World v2
このスクラップは2ヶ月前にクローズされました