We have built a development environment using Dokcer when using Go and Gin. I'm using docker-compose. The DB used is mysql, and the OR mapper assumes the use of Gorm.
TL;DR It has the following directory structure. Dockerfile and docker-compose.yml.
** Directory structure **
├── docker
│   ├── docker.mysql.env
│   └── go
│       └── Dockerfile
├── docker-compose.yml
└── src
    └── app
docker/go/Dockerfile
FROM golang:1.10.3-alpine3.8
COPY src/app /go/src/app/
WORKDIR /go/src/app/
RUN apk update \
  && apk add --no-cache git \
  && go get github.com/gin-gonic/gin \
  && go get github.com/jinzhu/gorm \
  && go get github.com/go-sql-driver/mysql
EXPOSE 8080
docker/docker.mysql.env
MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE=go-gin-app
MYSQL_USER=root
MYSQL_PASSWORD=password
docker-compose.yml
services:
  app:
    container_name: app
    build:
      context: .
      dockerfile: ./docker/go/Dockerfile
    ports:
      - 3000:3000
    links:
      - database
    tty:
      true
    volumes:
      - ./src/app:/go/src/app
  database:
    restart: always
    image: mysql:5.7
    ports:
      - 3308:3306
    volumes:
      - mysql-datavolume:/var/lib/mysql
    env_file:
      - docker/docker.mysql.env
volumes:
  mysql-datavolume:
    driver: local
Dockerfile
This time I will only create a Go Dockerfile and mysql will specify in docker-compose.yml to use the base image.
FROM golang:1.10.3-alpine3.8
COPY src/app /go/src/app/
WORKDIR /go/src/app/
RUN apk update \
  && apk add --no-cache git \
  && go get github.com/gin-gonic/gin \
  && go get github.com/jinzhu/gorm \
  && go get github.com/go-sql-driver/mysql
EXPOSE 8080
The file directly under src / app is specified as the volume.
Also, since the base image of aliphine is specified, Gin and Gorm related packages are installed with apk.
docker-compose.yml
services:
  app:
    container_name: app
    build:
      context: .
      dockerfile: ./docker/go/Dockerfile
    ports:
      - 3000:3000
    links:
      - database
    tty:
      true
    volumes:
      - ./src/app:/go/src/app
  database:
    restart: always
    image: mysql:5.7
    ports:
      - 3307:3306
    volumes:
      - mysql-datavolume:/var/lib/mysql
    env_file:
      - docker/docker.mysql.env
volumes:
  mysql-datavolume:
    driver: local
I created the mysql env file separately, so specify it with ʻenv_file.  Port 3306 is often used by local mysql, so 3307` is specified.
Create main.go directly under src / app and write the code to output the familiar hello world.
package main
import "fmt"
func main() {
        fmt.Println("Hello, world")
}
Then, output hello world with the following command.
docker-compose exec app go run main.go
Was hello world output?
It was surprisingly easy to build a Go + Gin environment.
After all, using Docker makes it easier to build an environment!
Recommended Posts