无法在Golang中ping通MySQL数据库的Docker。

huangapple go评论85阅读模式
英文:

Unable to ping mysql db docker in golang

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对golang、docker和mysql都不太熟悉。我正在尝试使用golang在我的macOS上连接到在docker中运行的mysql。

以下是代码:

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()
}

我使用以下命令运行docker:

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

我得到以下错误:

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

docker正在本地运行。我使用命令行创建了一个名为test_db的测试数据库:

mysql> create database test_db;

然后执行了以下命令:

mysql> show databases;

结果如下:

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

请帮助我理解我的错误或者我漏掉了什么?

英文:

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?

答案1

得分: 0

我在这个docker-compose.yml文件中使用了host.docker.internal来在docker中创建mysql服务器。

版本:'3'

服务:

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"

使用以下命令运行docker镜像:

docker-compose -f docker-compose.yml up

然后使用以下命令连接到docker mysql实例:

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

然后创建一个单独的用户并授予该用户所有权限。

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;

这样可以帮助我在macOS上本地连接到运行在docker上的mysql服务器。

英文:

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.

huangapple
  • 本文由 发表于 2022年10月10日 10:01:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/74009618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定