0
0

go, gin, docker-composeで環境構築する方法

Last updated at Posted at 2023-11-25

バックエンドにgoを使ってAPIを作る方法をまとめてみた。

●まずはディレクトリ構造
↓こんな感じ

myapp/
├── Dockerfile
├── docker-compose.yml
└── app/
    ├── main.go
    └── go.mod

Dockerfileの作成

FROM golang:1.18
WORKDIR /app
COPY app/go.* ./
RUN go mod download
COPY app/*.go ./
RUN go build -o /myapp
EXPOSE 8080
CMD ["/myapp"]

docker-compose.ymlの作成

version: '3.8'
services:
  web:
    build: .
    ports:
      - "8080:8080"
    volumes:
      - ./app:/app

Goアプリケーションの作成

myapp/app/main.goとmyapp/app/go.modを作成。 ・go.modには以下の内容を記述
module myapp
go 1.18
require github.com/gin-gonic/gin v1.8.1

・main.goには以下の内容を記述

package main
import (
    "github.com/gin-gonic/gin"
)
func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "goの勉強開始!",
        })
    })
    r.Run()
}

コンテナをビルドして立ち上げる

docker-compose up --build
0
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
0
0