skip to Main Content

Attempting to create a golang mysql multi container app. Similar to docker example https://docs.docker.com/get-started/07_multi_container/

I do not understand why connection is refused.

dial tcp 127.0.0.1:3306: connect: connection refused

Here is my docker-compose.yaml

version: '3.7'

services:
  api:
    # api service starts ok but fatal error at db connection
  maria-db:
    image: mariadb:10-focal
    container_name: s-maria-db
    command: '--default-authentication-plugin=mysql_native_password'
    restart: always
    healthcheck:
      test: ["CMD-SHEL", "mysqladmin ping -h 127.0.0.1 --password=secret --silent"]
      interval: 3s
      retries: 5
      start_period: 30s
    expose:
      - "3306:3306"
    # setting some env vars to create the DB
    environment:
      MYSQL_ROOT_PASSWORD: "secret"
      MYSQL_DATABASE: "s_db"

    # we mount a data volume to make sure we don't lose data
    volumes:
      - db-data:/var/lib/mysql

volumes:
  db-data:


Here is my go-code to connect to db

func Connect() (*sql.DB, error) {
    db, err := sql.Open("mysql", "root:secret@/s_db")
    
    if err != nil {
        return nil, err
    }

    defer db.Close()

    pingErr := db.Ping()
    if pingErr != nil {
        return nil, pingErr
    }
    return db, nil
}

I always see dial tcp 127.0.0.1:3306: connect: connection refused

I can

docker exec -it s-maria-db bash
.
.
.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| s_db        |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

and see the db is configured correctly , but I can never connect to it.

2

Answers


  1. Chosen as BEST ANSWER

    Additionally updated go with

        for i := 0; i < 60; i++ {
            if err := db.Ping(); err == nil {
                fmt.Print("We are connected!")
                break
            }
            time.Sleep(time.Second)
        }
    

    as seen https://github.com/docker/awesome-compose/blob/master/nginx-golang-mysql/backend/main.go


  2. try to connect using container’s name hence docker composer uses docker network. That allows you to connect via container’s name as a network alias.

    func Connect() (*sql.DB, error) {
    db, err := sql.Open("mysql", "root:secret@tcp(s-maria-db)/s_db")
    
    if err != nil {
        return nil, err
    }
    
    defer db.Close()
    
    pingErr := db.Ping()
    if pingErr != nil {
        return nil, pingErr
    }
    return db, nil
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search