Search code examples
mysqldockertcpdocker-composego-gorm

panic: dial tcp 127.0.0.1:3306: connect: connection refused


I'm trying connect mysql server from docker using golang gin gorm.

The build itself has succeeded, but as shown in the title, the following error has been issued.

panic: dial tcp 127.0.0.1:3306: connect: connection refused

Trying to connect in this way

func dbConnect() *gorm.DB {
    db, err := gorm.Open("mysql", "docker:password@/godocker")

    if err != nil {
        panic(err.Error())
    }

    return db
}

  • docker-compose.yml
db:
    image: mysql:5.7.26
    environment:
      MYSQL_USER: docker
      MYSQL_ROOT_PASSWORD: password
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: godocker
    ports:
      - "3306:3306"

Result of hitting docker-compose ps command

      Name                   Command             State                 Ports
------------------------------------------------------------------------------------------
gin-docker_api_1   /bin/sh -c gin -i run         Up      0.0.0.0:3001->3001/tcp
gin-docker_db_1    docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp, 33060/tcp

Thanks


Solution

  • You should connect to connect via container's name instead

    db:
      image: mysql:5.7.26
      container_name: godockerDB
      environment:
        MYSQL_USER: docker
        MYSQL_ROOT_PASSWORD: password
        MYSQL_PASSWORD: password
        MYSQL_DATABASE: godocker
      ports:
        - "3306:3306"
    

    Then you can conenct via container name

    func dbConnect() *gorm.DB {
    db, err := gorm.Open("mysql", "docker:password@tcp(godockerDB)/godocker")
    
    if err != nil {
        panic(err.Error())
    }
    
        return db
    }