Home > Enterprise >  connection refused with go&mysql&docker
connection refused with go&mysql&docker

Time:12-29

I'm trying to connect mysqlDB which is created on Docker from my local go file.

main.go

package main

import (
    "database/sql"
    "fmt"

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

func main() {
    fmt.Println("Hello")
    // All following 4 codes won't connect to the database.
        // "db01" is docker container name. "test" is db name.
    // db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/test")
    // db, err := sql.Open("mysql", "root:password@tcp(localhost)/test")
    // db, err := sql.Open("mysql", "root:password@tcp(db01)/test")
    db, err := sql.Open("mysql", "root:password@tcp(db01:3306)/test")

    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()
    fmt.Println(db)
    err = db.Ping()
    if err != nil {
        fmt.Println(err)
    }
}

docker command

docker run --name db01 -dit -e MYSQL_ROOT_PASSWORD=password mysql:latest

error message

when trying with localhost:3306

dial tcp [::1]:3306: connect: connection refused

when trying with db01

dial tcp: lookup db01: no such host

mysql db is created on docker container without any issue, so I think connection between go file and docker container is not going well.

Do I have to create docker-compose.yml file? I want to connect without it at now.

Thank you.

CodePudding user response:

You created a docker container and ran MySQL in it. That container will have its own network address. You can publish a port of that container on your localhost by running:

docker run --name db01 -p 3306:3306 -dit -e MYSQL_ROOT_PASSWORD=password mysql:latest

This will publish the port 3306 of the container on localhost:3306. Then you can connect to it.

Alternatively, you can get the IP address of the container running using docker inspect <containerId>, and connect to that address:3306.

  • Related