dslkchyv673627 2018-07-18 22:14
浏览 367
已采纳

无法连接到在我的Mac上运行的mysql

I am using golang app , wrapped up in a docker container to connect to mysql db running on my localhost(not container). Her eis what I tried: Docker File

FROM artifactory.cloud.com//golang:1.10-alpine3.7

RUN mkdir -p /go/src/github.kdc.mafsafdfsacys.com/perfGo/
WORKDIR /go/src/github.kdc.mafsafdfsacys.com/perfGo
COPY ./ $WORKDIR
RUN apk update && apk upgrade
RUN go build

RUN chmod +x ./entrypoint.sh
RUN ls
RUN chmod +x ./perfGo
ENTRYPOINT ["./entrypoint.sh"]

perfGo.go

package main

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

func main() {
    db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/testdb")
    checkErr(err)
    _,dbErr := db.Exec("USE testdb")
    if err != nil {
        panic(dbErr)
    }

    // insert
    _, inErr := db.Query("INSERT INTO books VALUES('rewyrewryewwrewyt','dsfdsfs','fdsfasaf','55')")

    defer db.Close()
    // if there is an error inserting, handle it
    if inErr != nil {
        panic(inErr.Error())
    }

}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

entrypoint.sh

!/usr/bin/env bash

./perfGo

Command am using to build is

docker build .

command used to run the container: docker run -p 3306:3306 -ti

The error that I see is

panic: dial tcp 127.0.0.1:3306: connect: connection refused

goroutine 1 [running]:
main.main()
    /go/src/github.kdc.capitalone.com/midnight-tokens/perfGo/perf.go:22 +0x1d4

If I run the binary without the container, it runs totally fine on my mac, but when I try to run it as part of docker container, it fails to connect

  • 写回答

1条回答 默认 最新

  • duan5801 2018-07-18 22:25
    关注

    If the application is running in a container, and the database is on the host, then the address of the database from the container is obviously not localhost (That is the loopback device of the container).

    If you are using Docker For Mac, then you can use:

    "docker.for.mac.localhost:3306" in place of "localhost:3306"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题