Home > Software design >  panic: dial tcp: lookup bookstoreDB on 172.22.64.1:53: no such host
panic: dial tcp: lookup bookstoreDB on 172.22.64.1:53: no such host

Time:08-02

First post here! Trying to connect to a mysql server from docker using golang,gin, and gorm but I'm having issues connecting to the server through gorm.

Here is the error I am getting :

panic: dial tcp: lookup bookstoreDB on 172.22.64.1:53: no such host

Here is how I am trying to initiate the connection through gorm:

func Connect() {
    d, err := gorm.Open("mysql", "docker:password@tcp(bookstoreDB)/bookstore")
    if err != nil {
        panic(err)
    }

    db = d
}

Here's what my docker-compose.yml file looks like:

version: "3.8"

services: 
  mysql_server:
    image: mysql:8.0
    container_name: bookstoreDB
    environment: 
      - MYSQL_DATABASE=bookstore
      - MYSQL_USER=docker
      - MYSQL_PASSWORD=password
      - MYSQL_ROOT_PASSWORD=password
    ports:
      - "3306:3306"

Here is what appears when I run the "docker-compose ps" command:

   Name                 Command             State                 Ports
-------------------------------------------------------------------------------------
bookstoreDB   docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp, 33060/tcp

Here is a screenshot of my project structure :

bookstore project structure

Thank you for your time.

CodePudding user response:

Here you are trying to connect to a hostname that is totally unknown out of the docker-compose cluster.

d, err := gorm.Open("mysql", "docker:password@tcp(bookstoreDB)/bookstore")

bookstoreDB is totally unknown here. The idea of mapping the ports (as you are doing with mySql's one :

   Name                 Command             State                 Ports
-------------------------------------------------------------------------------------
bookstoreDB   docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp, 33060/tcp

Is to use that mapping as connection to the database (not the container's intra host name).

Change your code so you connect to your localhost:3306 instead. This is pseudocode as don't understand the language:

d, err := gorm.Open("mysql", "<docker:password@tcp(localhost)/bookstore>")
  • Related