diff --git a/Dockerfile b/Dockerfile index 01c750f..2a54028 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,4 +3,5 @@ WORKDIR /app/dtm RUN go env -w GO111MODULE=on RUN go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct EXPOSE 8080 +ENV IS_DOCKER 1 CMD [ "/bin/bash", "-c", "go build app/main.go && /app/dtm/main" ] diff --git a/common/types.go b/common/types.go index d82dc54..707a15f 100644 --- a/common/types.go +++ b/common/types.go @@ -4,6 +4,7 @@ import ( "database/sql" "fmt" "regexp" + "strings" "time" "github.com/sirupsen/logrus" @@ -87,6 +88,9 @@ func (op *tracePlugin) Initialize(db *gorm.DB) (err error) { } func GetDsn(conf map[string]string) string { + if IsDocker() { + conf["host"] = strings.Replace(conf["host"], "localhost", "host.docker.internal", 1) + } return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local", conf["user"], conf["password"], conf["host"], conf["port"], conf["database"]) } diff --git a/common/utils.go b/common/utils.go index 073c3fa..65dd3a9 100644 --- a/common/utils.go +++ b/common/utils.go @@ -188,6 +188,9 @@ func init() { // RestyClient.SetRetryCount(2) // RestyClient.SetRetryWaitTime(1 * time.Second) RestyClient.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { + if IsDocker() { + r.URL = strings.Replace(r.URL, "localhost", "host.docker.internal", 1) + } logrus.Printf("requesting: %s %s %v %v", r.Method, r.URL, r.Body, r.QueryParam) return nil }) @@ -269,3 +272,7 @@ func GetFuncName() string { pc, _, _, _ := runtime.Caller(1) return runtime.FuncForPC(pc).Name() } + +func IsDocker() bool { + return os.Getenv("IS_DOCKER") != "" +} diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..c5fef8a --- /dev/null +++ b/compose.yml @@ -0,0 +1,29 @@ +version: '3.3' +services: + mysql: + image: 'mysql:5.7' + environment: + MYSQL_ROOT_PASSWORD: my-secret-pw + TZ: Asia/shanghai + command: + [ + '--character-set-server=utf8mb4', + '--collation-server=utf8mb4_unicode_ci', + '--default-time-zone=+8:00', + ] + ports: + - '3306:3306' +services: + dtm: + image: 'mysql:5.7' + environment: + MYSQL_ROOT_PASSWORD: my-secret-pw + TZ: Asia/shanghai + command: + [ + '--character-set-server=utf8mb4', + '--collation-server=utf8mb4_unicode_ci', + '--default-time-zone=+8:00', + ] + ports: + - '3306:3306' \ No newline at end of file