dslkchyv673627
2018-07-18 22:14 阅读 294

无法连接到在我的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 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"

    点赞 1 评论 复制链接分享

相关推荐