在 docker-compose 中 MySQL 连接被拒绝

问题描述 投票:0回答:2

我在 docker-compose 中从 golang 应用程序连接到 MySQL 时遇到问题。我可以从控制台连接到数据库: mysql -u user -D data -h 0.0.0.0 -P3306 -p 但是,使用 docker-compose 时无法连接。

我的docker-compose.yml

version: '3'

services:

  app:
    build: ./
    volumes:
      - ./internal/app:/app
      - ./logs:/var/log/parser
    links:
      - db

  db:
    image: mysql:8
    container_name: mysqldb
    ports:
      - "3306:3306"
    volumes:
      - ./docker/mysql/conf:/etc/mysql/conf/conf.d
      - ./docker/mysql/logs/:/var/log/mysql
      - ./docker/mysql/init:/docker-entrypoint-initdb.d
      - ./docker/mysql/data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: pass
      MYSQL_DATABASE: data
      MYSQL_USER: user
      MYSQL_PASSWORD: pass

在我的应用程序 main.go 中

    dbConfig := mysql.NewConfig()
    dbConfig.User = "user"
    dbConfig.Passwd = "pass"
    dbConfig.Addr = "mysqldb"
    dbConfig.DBName = "data"
    dbConfig.Net = "tcp"
    db, err := sql.Open("mysql", dbConfig.FormatDSN())
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

但我收到此错误:

panic: dial tcp 172.20.0.2:3306: connect: connection refused
mysql docker go docker-compose
2个回答
4
投票

我认为你的 golang 服务在 MySQL 服务之前启动。所以你必须先启动 MySQL 服务,然后启动 golang 服务,所以,使用

depends_on
来实现这一点。

带有depends_on的新docker-compose.yml

version: '3'

services:

  app:
    build: ./
    volumes:
      - ./internal/app:/app
      - ./logs:/var/log/parser
    depends_on:
      - mysqldb
    links:
      - db

  db:
    image: mysql:8
    container_name: mysqldb
    ports:
      - "3306:3306"
    volumes:
      - ./docker/mysql/conf:/etc/mysql/conf/conf.d
      - ./docker/mysql/logs/:/var/log/mysql
      - ./docker/mysql/init:/docker-entrypoint-initdb.d
      - ./docker/mysql/data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: pass
      MYSQL_DATABASE: data
      MYSQL_USER: user
      MYSQL_PASSWORD: pass


0
投票

我不知道这是否是最好的解决方案,但是如果你在你的golang容器中指定

重新启动:始终

,容器将重新启动,直到连接到数据库。

version: '3'

services:

  app:
    restart: always
    build: ./
    volumes:
      - ./internal/app:/app
      - ./logs:/var/log/parser
    depends_on:
      - mysqldb
    links:
      - db

  db:
    image: mysql:8
    container_name: mysqldb
    ports:
      - "3306:3306"
    volumes:
      - ./docker/mysql/conf:/etc/mysql/conf/conf.d
      - ./docker/mysql/logs/:/var/log/mysql
      - ./docker/mysql/init:/docker-entrypoint-initdb.d
      - ./docker/mysql/data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: pass
      MYSQL_DATABASE: data
      MYSQL_USER: user
      MYSQL_PASSWORD: pass
© www.soinside.com 2019 - 2024. All rights reserved.