2018-07-18 22:14
浏览 355


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
RUN apk update && apk upgrade
RUN go build

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


package main

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

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

    // 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 {


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


!/usr/bin/env bash


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 connect: connection refused

goroutine 1 [running]:
    /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"

    打赏 评论

相关推荐 更多相似问题