4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go(Gorm)+MySQLなDocker環境でdial tcp connection refusedが発生した際の対処法

Posted at

エラー内容

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!")
	}
}

参考

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?