dslkchyv673627 2018-07-18 14: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 14: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"

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部