我不明白为什么我不能使用Docker compose golang mariadb/mysql多容器应用程序连接到mysql

bgtovc5b  于 2023-04-03  发布在  Go
关注(0)|答案(2)|浏览(123)

尝试创建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 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:

下面是我的go-code连接到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
}

我总是看到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                |
+--------------------+

并查看数据库是否配置正确,但我永远无法连接到它。

py49o6xq

py49o6xq1#

尝试使用容器的名称进行连接,因此docker composer使用docker network。这允许您通过容器的名称作为网络别名进行连接。

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

}

ecbunoof

ecbunoof2#

另外更新了go with

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

如图所示https://github.com/docker/awesome-compose/blob/master/nginx-golang-mysql/backend/main.go

相关问题