エラー内容
docker-compose up
時に以下のエラーが発生しました。
[error] failed to initialize database, got error dial tcp 172.19.0.2:3306: connect: connection refused
原因
docker-composeでcontainer_name
を指定していなかったため
対処法
Before
docker-compose.yml
version: "3.9"
services:
backend:
build: .
ports:
- 8000:8000
volumes:
- .:/app
depends_on:
- db
db:
image: mysql:5.7.22
restart: always
environment:
MYSQL_DATABASE: ambassador
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
volumes:
- .dbdata:/var/lib/mysql
ports:
- 33066:3306
main.go
var DB *gorm.DB
func Connect() {
var err error
DB, err = gorm.Open(mysql.Open("root:root@tcp(db:3306)/ambassador"), &gorm.Config{})
if err != nil {
panic("Could not connect with database!")
}
}
After
docker-compose.yml
container_name: godockerDB
を追加
version: "3.9"
services:
backend:
build: .
ports:
- 8000:8000
volumes:
- .:/app
depends_on:
- db
db:
image: mysql:5.7.22
container_name: godockerDB # 追加
restart: always
environment:
MYSQL_DATABASE: ambassador
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
volumes:
- .dbdata:/var/lib/mysql
ports:
- 33066:3306
main.go
godockerDB
を指定
var DB *gorm.DB
func Connect() {
var err error
# container_nameを指定
DB, err = gorm.Open(mysql.Open("root:root@tcp(godockerDB)/ambassador"), &gorm.Config{})
if err != nil {
panic("Could not connect with database!")
}
}
参考