go+mysql 项目的 docker-compose

1,847 阅读1分钟

最近在尝试给 go 项目打包,为了方便程序的运行,将程序用 docker 容器执行。

Go 文件夹 和 MySQL 下分别放置了 build 需要的 Dockerfile,其中 MySQL 文件夹放置了数据库需要初始化的数据 test.sql。

first-docker-compose
│
│
└───Go
│   │
│   │   Dockerfile
│   │   main.go
│   └───go.mod
│       │   go.sum
│   
└───MySQL
    │
    │   Dockerfile
    │   test.sql

Go/Dockerfile

# syntax=docker/dockerfile:1

FROM golang:1.16-alpine

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /docker-gs-ping

EXPOSE 8080

CMD [ "/docker-gs-ping" ]

Go/go.mod

module first-docker-compose

go 1.17

require (
   github.com/go-sql-driver/mysql v1.6.0
   github.com/labstack/echo/v4 v4.7.2
)

require (
   github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
   github.com/labstack/gommon v0.3.1 // indirect
   github.com/mattn/go-colorable v0.1.11 // indirect
   github.com/mattn/go-isatty v0.0.14 // indirect
   github.com/valyala/bytebufferpool v1.0.0 // indirect
   github.com/valyala/fasttemplate v1.2.1 // indirect
   golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect
   golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f // indirect
   golang.org/x/sys v0.0.0-20211103235746-7861aae1554b // indirect
   golang.org/x/text v0.3.7 // indirect
   golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect
)

Go/mian.go

package main

import (
   "database/sql"
   "fmt"
   _ "github.com/go-sql-driver/mysql"
   "log"
)

func main() {
   cnn, err := sql.Open("mysql", "root:123456@tcp(mydb:3306)/test_db")
   //cnn, err := sql.Open("mysql", "root:123456@tcp(host.docker.internal:3306)/test_db")
   if err != nil {
      log.Fatal(err)
   }

   id := 1
   var name string

   if err := cnn.QueryRow("SELECT name FROM test_tb WHERE id = ? LIMIT 1", id).Scan(&name); err != nil {
      log.Fatal(err)
   }

   fmt.Println(id, name)
}

MySQL/Dockerfile

FROM mysql:latest
COPY test.sql /docker-entrypoint-initdb.d/test.sql

MySQL/test.sql

CREATE DATABASE test_db;

Use test_db;

Create table `test_tb` (id int, name varchar(20));

Insert into test_tb (id, name) values (1, 'test-user');

docker-compose.yaml

version: '3'
services:
  mydb:
    build:
      context: ./MySQL
    environment:
      MYSQL_ROOT_PASSWORD: 123456
    container_name: golang_db
    ports:
      - "3306:3306"
    tty: true
  app:
    build:
      context: ./Go
    volumes:
      - "./Go:/workspace"
    container_name: golang_app
    ports:
      - "8080:8080"
    tty: true
    depends_on:
      - mydb

执行 docker-compose up --build 执行 compose,此时数据库 MySQL 映射在 3306 端口

image.png

app 项目执行结果:

image.png