I do not understand why I can not connect to mysql using docker compose golang mariadb/mysql multi container app

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

I do not understand why I can not connect to mysql using docker compose golang mariadb/mysql multi container app

问题

尝试创建一个使用Golang和MySQL的多容器应用程序,类似于Docker示例https://docs.docker.com/get-started/07_multi_container/。

我不明白为什么连接被拒绝。

dial tcp 127.0.0.1:3306: connect: connection refused

这是我的docker-compose.yaml文件:

version: '3.7'

services:
  api:
    # api服务正常启动,但在连接数据库时出现致命错误
  maria-db:
    image: mariadb:10-focal
    container_name: s-maria-db
    command: '--default-authentication-plugin=mysql_native_password'
    restart: always
    healthcheck:
      test: ["CMD-SHEL", "mysqladmin ping -h 127.0.0.1 --password=secret --silent"]
      interval: 3s
      retries: 5
      start_period: 30s
    expose:
      - "3306:3306"
    # 设置一些环境变量来创建数据库
    environment:
      MYSQL_ROOT_PASSWORD: "secret"
      MYSQL_DATABASE: "s_db"

    # 挂载数据卷以确保不丢失数据
    volumes:
      - db-data:/var/lib/mysql

volumes:
  db-data:

这是我连接数据库的Go代码:

func Connect() (*sql.DB, error) {
	db, err := sql.Open("mysql", "root:secret@/s_db")
	
	if err != nil {
		return nil, err
	}

	defer db.Close()

	pingErr := db.Ping()
	if pingErr != nil {
		return nil, pingErr
	}
	return db, nil
}

我总是看到dial tcp 127.0.0.1:3306: connect: connection refused的错误。

我可以执行以下命令:

docker exec -it s-maria-db bash
.
.
.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| s_db        |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

并且可以看到数据库已正确配置,但我无法连接到它。

英文:

Attempting to create a golang mysql multi container app. Similar to docker example https://docs.docker.com/get-started/07_multi_container/

I do not understand why connection is refused.

dial tcp 127.0.0.1:3306: connect: connection refused

Here is my docker-compose.yaml

version: '3.7'

services:
  api:
    # api service starts ok but fatal error at db connection
  maria-db:
    image: mariadb:10-focal
    container_name: s-maria-db
    command: '--default-authentication-plugin=mysql_native_password'
    restart: always
    healthcheck:
      test: ["CMD-SHEL", "mysqladmin ping -h 127.0.0.1 --password=secret --silent"]
      interval: 3s
      retries: 5
      start_period: 30s
    expose:
      - "3306:3306"
    # setting some env vars to create the DB
    environment:
      MYSQL_ROOT_PASSWORD: "secret"
      MYSQL_DATABASE: "s_db"

    # we mount a data volume to make sure we don't lose data
    volumes:
      - db-data:/var/lib/mysql

volumes:
  db-data:


Here is my go-code to connect to db

func Connect() (*sql.DB, error) {
	db, err := sql.Open("mysql", "root:secret@/s_db")
	
	if err != nil {
		return nil, err
	}

	defer db.Close()

	pingErr := db.Ping()
	if pingErr != nil {
		return nil, pingErr
	}
	return db, nil
}

I always see dial tcp 127.0.0.1:3306: connect: connection refused

I can

docker exec -it s-maria-db bash
.
.
.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| s_db        |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

and see the db is configured correctly , but I can never connect to it.

答案1

得分: 2

尝试使用容器的名称进行连接,因为Docker Compose使用Docker网络。这样可以通过容器的名称作为网络别名进行连接。

func Connect() (*sql.DB, error) {
    db, err := sql.Open("mysql", "root:secret@tcp(s-maria-db)/s_db")
    
    if err != nil {
        return nil, err
    }

    defer db.Close()

    pingErr := db.Ping()
    if pingErr != nil {
        return nil, pingErr
    }
    return db, nil
}
英文:

try to connect using container's name hence docker composer uses docker network. That allows you to connect via container's name as a network alias.

func Connect() (*sql.DB, error) {
db, err := sql.Open("mysql", "root:secret@tcp(s-maria-db)/s_db")

if err != nil {
    return nil, err
}

defer db.Close()

pingErr := db.Ping()
if pingErr != nil {
    return nil, pingErr
}
return db, nil

}

答案2

得分: 2

此外,更新的代码如下:

for i := 0; i < 60; i++ {
	if err := db.Ping(); err == nil {
		fmt.Print("我们已连接!")
		break
	}
	time.Sleep(time.Second)
}

代码来源:https://github.com/docker/awesome-compose/blob/master/nginx-golang-mysql/backend/main.go

英文:

Additionally updated go with

	for i := 0; i &lt; 60; i++ {
		if err := db.Ping(); err == nil {
			fmt.Print(&quot;We are connected!&quot;)
			break
		}
		time.Sleep(time.Second)
	}

as seen https://github.com/docker/awesome-compose/blob/master/nginx-golang-mysql/backend/main.go

huangapple
  • 本文由 发表于 2023年3月31日 00:59:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891043.html
匿名

发表评论

匿名网友

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

确定