Home > Mobile >  Unable to ping mysql db docker in golang
Unable to ping mysql db docker in golang

Time:10-15

I am new to golang, docker and mysql. I am trying to connect to mysql running in docker locally on my macos using golang.

Here is the code:

`package main

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

func dbConn() *sql.DB {
    db, err := sql.Open("mysql", "root:Abc123$#@tcp(172.17.0.2:3306)/test")
    if err != nil {
        log.Printf("Error %s when opening DB connection\n", err)
        return nil
    }
    db.SetMaxOpenConns(10)
    db.SetMaxIdleConns(10)
    db.SetConnMaxLifetime(time.Minute * 2)

    ctx, cancelfunc := context.WithTimeout(context.Background(), time.Second)
    defer cancelfunc()
    err = db.PingContext(ctx)
    if err != nil {
        log.Printf("Error %s pinging DB", err)
        return db
    }
    log.Print("Connected to the DB successfully\n")

    defer func() {
        err := db.Close()
        if err != nil {
            log.Print(err)
        }
    }()
    return db
}

func main() {
    db := dbConn()
    defer db.Close()
}`

I am running docker with the following command:

docker run --name mysql -e MYSQL_ROOT_PASSWORD=abcd1234 -p 3306:3306 -d mysql:8.0.30

I get the following error:

Error dial tcp 172.17.0.2:3306: i/o timeout pinging DB

docker is running locally. I created a test-db with command-line:

`mysql> create database test_db;`

and then did a


mysql> show databases;

 -------------------- 
| Database           |
 -------------------- 
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_db            |
 -------------------- 
6 rows in set (0.00 sec)

Please help me understand my mistake here? Or what am I missing?

CodePudding user response:

I used host.docker.internal in this docker-compose.yml file to create the mysql sever in docker.

version: '3'

services:

  mysql-development:
    image: mysql:8.0.30
    environment:
  MYSQL_ROOT_PASSWORD: xyz1234
  MYSQL_DATABASE: test
  ports:
    - "3306:3306"
  extra_hosts:
    - "host.docker.internal:host-gateway"

Used this to run the docker image:

docker-compose -f docker-compose.yml up

Then connected to docker mysql instance using:

docker exec -it 24f058c73227 mysql -P 3306 --protocol=tcp -u root -p

Then created a separate user and granted all privileges to the new user.

mysql> CREATE user ‘user2’@‘172.19.0.1' IDENTIFIED BY ‘xyz1234’;
mysql> GRANT ALL PRIVILEGES ON *.* TO 'user2'@'172.19.0.1' WITH GRANT 
OPTION;

This helped me connect to mysql server running on the docker locally on macos.

  • Related