Docker+Go+GinのAPI開発環境を5分で作る

大瀧

2024.02.10

144

こんにちは、オオタキです。


この記事はDocker+Go+Ginで簡単なAPI開発環境を作る方法を解説します。

3分で読めて5分で実践できるのでよかったら読んでいってください。


早速解説していきます。

本題

1. docker init でファイルを自動生成する

まず初めにDockerfile、docker-compose.yaml、.dockerignoreを作成していきます。

docker init コマンドを実行すると順番に以下の選択・入力を求められるので、

聞かれるままに答えていくと自動的にDockerfileなどが生成されます。(公式のブログ


  • 使用言語
  • バージョン
  • メインパッケージの相対ディレクトリ
  • サーバーのリッスンポート


$ docker init

Welcome to the Docker Init CLI!

This utility will walk you through creating the following files with sensible defaults for your project:
 - .dockerignore
 - Dockerfile
 - docker-compose.yaml

Let's get started!

? What application platform does your project use? Go
? What version of Go do you want to use? 1.18
? What's the relative directory (with a leading .) of your main package? .
? What port does your server listen on? 8080

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: docker-compose.yaml

✔ Your Docker files are ready!

Take a moment to review them and tailor them to your application.

When you're ready, start your application by running: docker compose up --build -d

Your application will be available at http://localhost:8080

To stop your application, run: docker compose down

2. go mod init で新しいGoモジュールを初期化する

次に go mod init コマンドを実行してGoモジュールを初期化します。

helloworldの部分はプロジェクト名なので何でも良いです。

$ go mod init helloworld

このコマンドを実行するとgo.modが生成されます。

3. go get でGinをインストールする

go.modが作成できたら、go get コマンドを実行してGinをインストールします。

$ go get -u github.com/gin-gonic/gin

このコマンドを実行するとgo.modが変更され、go.sumが生成されます。

4. main.goを用意する

最後に main.go を作成し、以下のコードをコピペします。

内容としては /hellowworld に向けてGETすると Hello World! が返ってくるという簡単な内容です。

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/helloworld", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"message": "Hello World!",
		})
	})
	r.Run()
}


ここまで作成したら、プロジェクト内のファイルは以下のようになっているはずです。

不足している場合は手順を戻って生成しましょう。

.
├── Dockerfile
├── docker-compose.yaml
├── .dockerignore
├── go.mod
├── go.sum
└── main.go

5. docker compose up --build でコンテナをビルドして立ち上げる

$ docker compose up --build を実行します。

Listening and serving HTTP on :8080 と表示されたらOKです。

 ✔ Container docker_init_test-server-1 Recreated                                    0.1s
Attaching to docker_init_test-server-1
docker_init_test-server-1 | [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
docker_init_test-server-1 |
docker_init_test-server-1 | [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
docker_init_test-server-1 | - using env:   export GIN_MODE=release
docker_init_test-server-1 | - using code:   gin.SetMode(gin.ReleaseMode)
docker_init_test-server-1 |
docker_init_test-server-1 | [GIN-debug] GET  /helloworld        --> main.main.func1 (3 handlers)
docker_init_test-server-1 | [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
docker_init_test-server-1 | Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
docker_init_test-server-1 | [GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
docker_init_test-server-1 | [GIN-debug] Listening and serving HTTP on :8080

6. curlでレスポンスが返ってくるか確認

サーバーが立ち上がったはずなのでリクエストを投げて確認してみましょう。

curlコマンドを使って /helloworld に向けてGETリクエストを投げます。

$ curl http://localhost:8080/helloworld


以下のようなレスポンスが返ってきていればOKです。

 % curl http://localhost:8080/helloworld
{"message":"Hello World!"}%

おまけ

docker compose up --buildでエラーが出るとき

エラー例)

 => ERROR [build 3/4] RUN --mount=type=cache,target=/go/pkg/mod/   --mount=type=bind,source=go.sum,target=go.sum    0.2s
------
 > [build 3/4] RUN --mount=type=cache,target=/go/pkg/mod/   --mount=type=bind,source=go.sum,target=go.sum   --mount=type=bind,source=go.mod,target=go.mod   go mod download -x:
#0 0.205 go: errors parsing go.mod:
#0 0.205 /src/go.mod:3: invalid go version '1.21.3': must match format 1.23
------
failed to solve: executor failed running [/bin/sh -c go mod download -x]: exit code: 1


こんなエラーが発生したら、go.modに記載されているgoのバージョンを 1.21.31.21 のように修正し、

その後再度 $ docker comose up --build を実行します。


module helloworld

go 1.21.3 ←こいつを1.21に変更

require (
	github.com/bytedance/sonic v1.10.2 // indirect
	github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
	github.com/chenzhuoyu/iasm v0.9.1 // indirect
	github.com/gabriel-vasile/mimetype v1.4.3 // indirect
	github.com/gin-contrib/sse v0.1.0 // indirect
	github.com/gin-gonic/gin v1.9.1 // indirect


おそらくエラーが解消してサーバーが立ち上がります。

最後に

docker init コマンドが非常に便利ですね。


もし、ここまで記事を読んでDockerってそもそもなんぞやと思った方はこちらの記事で解説しているので合わせてどうそ。

https://build.yoku.co.jp/articles/a_y-w8d81

この記事をシェアする