LoginSignup
7
2

More than 1 year has passed since last update.

DockerでGO,Gin環境構築

Posted at

前提条件

Dockerがインストール済み

手順

フォルダ構成の作成

go
 - web
   - Dockerfile 
   - main.go
 - docker-compose.yml 

Dockerfileの記述

Dockerfile
FROM golang:latest
WORKDIR /go/src
docker-compose.yml
version: '3'
services:
  web:
    build: ./web
    tty: true
    volumes:
      - ./web:/go/src
    ports:
      - "3000:3000"

Docker起動~サーバーの起動まで

VSCodeのDocker拡張を使ってる場合は1,2番はGUIでもできます。

1.docker起動

docker-compose up

2.コンテナに入る(別ターミナルで)

docker-compose exec web bash

3.ginモジュールの追加

go mod init
go get github.com/gin-gonic/gin

4.main.goの記述

main.go
package main 

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

func main() {
    router := gin.Default()

    router.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello World",
        })
    })

    router.Run(":3000")
}

5.サーバーの起動

go run main.go

確認

ブラウザで「localhost:3000」にアクセス

jsonの内容が表示されれば完了です。

image.png

7
2
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
7
2