1
0

More than 1 year has passed since last update.

go + dockerでホットリロード機能を付ける

Posted at

DockerでGo言語の開発環境を作る方法でDocker+goの開発環境を作りました。今回はさらにホットリロード機能をつけていきます。

Dockerfileを修正

まず、Dockerfileに変更を加えていきます。Dockerfileの中身は以下の記事で取り上げたものをベースにしています。

FROM golang:1.19.1-alpine3.16![スクリーンショット 2023-07-08 202755.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3439167/54c6704b-3ded-2479-6c9e-b478adf86990.png)


WORKDIR /app

COPY backend/go.mod .
COPY backend/go.sum .
COPY backend/*air.toml .

RUN go mod download
RUN apk add --no-cache gcc
RUN apk add --no-cache musl-dev

COPY ./backend .

RUN go install github.com/cosmtrek/air@latest

CMD ["air"]
# CMD ["go", "run", "./cmd/api"]

.air.tomlを作成

次に以下の場所に.air.tomlを作成します。

project
├backend
│ └Dockerfile
│ └.air.toml ←新規作成
│ └cmd/
│  └─api/
│   └─main.go
└docker-compose.yml

.air.tomlは以下のとおりです。

# .air.toml
# Config file for [Air](https://github.com/cosmtrek/air) in TOML format

# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "."
tmp_dir = "tmp"

[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./tmp/main ./cmd/api"
# Binary file yields from `cmd`.
bin = "tmp/main"
# Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.
exclude_file = []
# This log file places in your tmp_dir.
log = "air.log"
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop running old binary when build errors occur.
stop_on_error = true
# Send Interrupt signal before killing process (windows does not support this feature)
send_interrupt = false
# Delay after sending Interrupt signal
kill_delay = 500 # ms

[log]
# Show log time
time = false

[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# Delete tmp directory on exit
clean_on_exit = true

以上で準備は終了です。

起動する

以下のとおりのコマンドを実行します。

docker compose build
docker compose up

以下のような表示がされれば成功です。
スクリーンショット 2023-07-08 202755.png

参考資料

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0