Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/backend/docker setup #6

Merged
merged 14 commits into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions typing-server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 基本イメージ
FROM golang:1.22.0 as builder

# 作業ディレクトリを設定
WORKDIR /app

# ソースコードをコピー
COPY . .

# 依存関係をインストール
RUN go mod download

# アプリケーションをビルド
RUN CGO_ENABLED=0 GOOS=linux go build -v -o server ./api/cmd/main.go

# 実行イメージ
FROM alpine:latest
RUN apk --no-cache add ca-certificates

# tzdataパッケージのインストール
RUN apk --no-cache add tzdata

WORKDIR /root

# ビルドしたバイナリをコピー
COPY --from=builder /app/server .

# アプリケーションの実行
CMD ["./server"]
72 changes: 72 additions & 0 deletions typing-server/api/cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package main

import (
"context"
"log"
"net/http"
"sync"
"time"

"github.com/go-sql-driver/mysql"
"github.com/su-its/typing/typing-server/api/presenter"
"github.com/su-its/typing/typing-server/domain/repository/ent"
)

func main() {
// 標準のログパッケージを使用
logger := log.Default()

// タイムゾーンの設定
jst, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
logger.Printf("failed to load location: %v", err)
return
}

// MySQLの接続設定
mysqlConfig := &mysql.Config{
DBName: "typing-db", // データベース名
User: "user", // ユーザー名
Passwd: "password", // パスワード
Net: "tcp", // ネットワークタイプ
Addr: "db:3306", // アドレス(Docker Compose内でのサービス名とポート)
ParseTime: true, // 時刻をtime.Timeで解析する
Loc: jst, // タイムゾーン
}

// entクライアントの初期化
entClient, err := ent.Open("mysql", mysqlConfig.FormatDSN())
if err != nil {
logger.Printf("failed to open ent client: %v", err)
return
} else {
logger.Println("ent client is opened")
}
shin0729 marked this conversation as resolved.
Show resolved Hide resolved

KinjiKawaguchi marked this conversation as resolved.
Show resolved Hide resolved
// スキーマの作成
if err := entClient.Schema.Create(context.Background()); err != nil {
logger.Printf("failed to create schema: %v", err)
return
} else {
logger.Println("schema is created")
}
shin0729 marked this conversation as resolved.
Show resolved Hide resolved

// ルートの登録
presenter.RegisterRoutes()

// WaitGroupの宣言
var wg sync.WaitGroup

// HTTPサーバーの非同期起動
wg.Add(1)
go func() {
defer wg.Done() // 関数終了時にWaitGroupをデクリメント

logger.Println("server is running at http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
logger.Printf("failed to listen and serve: %v", err)
shin0729 marked this conversation as resolved.
Show resolved Hide resolved
shin0729 marked this conversation as resolved.
Show resolved Hide resolved
}
}()

wg.Wait() // HTTPサーバーの終了を待機
}
20 changes: 20 additions & 0 deletions typing-server/api/controller/system/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package system

import (
"log"
"net/http"
)

// HealthCheck はヘルスチェックのためのハンドラー関数です。
func HealthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("API is running"))
if err != nil {
// エラーログを記録し、処理を終了します。
// 実際には、この時点でレスポンスヘッダーやボディがクライアントに送信されている可能性が高いため、
// http.Errorを呼び出すことは推奨されません。
// 代わりに、ログに記録するなどのサーバー側での対応が適切です。
log.Printf("failed to write response: %v", err)
shin0729 marked this conversation as resolved.
Show resolved Hide resolved
}
}

11 changes: 11 additions & 0 deletions typing-server/api/presenter/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package presenter

import (
"net/http"

"github.com/su-its/typing/typing-server/api/controller/system"
)

func RegisterRoutes() {
http.HandleFunc("/health", system.HealthCheck)
}
46 changes: 46 additions & 0 deletions typing-server/docker-compose.dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
services:
api:
depends_on:
db:
condition: service_healthy
build:
context: .
dockerfile: Dockerfile
volumes:
- ./api:/app
ports:
- "8080:8080"
networks:
app_net:
ipv4_address: '172.28.1.3'
extra_hosts:
- 'db:172.28.1.5'
db:
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
retries: 10
start_period: 30s

image: mysql:8.3.0
environment:
MYSQL_DATABASE: typing-db
MYSQL_USER: user
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
ports:
- "3307:3306"
volumes:
- db-data:/var/lib/mysql
networks:
app_net:
ipv4_address: '172.28.1.5'
volumes:
db-data:
networks:
app_net:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.28.1.0/24
shin0729 marked this conversation as resolved.
Show resolved Hide resolved
46 changes: 46 additions & 0 deletions typing-server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
services:
api:
depends_on:
db:
condition: service_healthy
build:
context: .
dockerfile: Dockerfile
volumes:
- ./api:/app
ports:
- "8080:8080"
networks:
app_net:
ipv4_address: '172.28.1.3'
extra_hosts:
- 'db:172.28.1.5'
db:
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
retries: 10
start_period: 30s

image: mysql:8.3.0
environment:
MYSQL_DATABASE: typing-db
MYSQL_USER: user
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
ports:
- "3307:3306"
volumes:
- db-data:/var/lib/mysql
networks:
app_net:
ipv4_address: '172.28.1.5'
volumes:
db-data:
networks:
app_net:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.28.1.0/24
shin0729 marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions typing-server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.22.0

require (
entgo.io/ent v0.13.1
github.com/go-sql-driver/mysql v1.7.0
github.com/google/uuid v1.6.0
)

Expand Down
2 changes: 2 additions & 0 deletions typing-server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
Expand Down
Loading