我有一个问题连接到MySQL从我的golang应用程序在docker-compose。我可以从控制台连接到db: 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
在我的app 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
我认为你的golang服务在MySQL服务之前启动。所以你必须先启动MySQL服务,然后再启动golang服务,所以,使用depends_on
来实现这一点。
新docker-compose。Yml with depends_on
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