docker – Cannot connect from one container to MySQL instance running in a different container-ThrowExceptions

Exception or error:

I cannot connect from one container to MySQL instance running in a different container. Setup is working on MacOS but not on windows.

I have docker-compose and two services: App and DB:

I am waiting for DB to be initialized. Then I try to ping db in my Go app.

This is the connection string: root:pass@tcp(db:3060)/orders?loc=Local&parseTime=1. User correct. Password correct. Hostname also correct. Port correct. But I got the error:

dial tcp 192.168.48.2:3060: connect: connection refused

Credentials are Ok because I can connect at the same time to DB from my host.

I am using Go MySQL Driver and MySQL 5.7. I tried also MySQL 8 – the same effect.

Below my docker-compose.yml

version: "3.7"
services:
  db:
    image: mysql:5.7
    container_name: golang-example-api-db
    # restart: on-failure
    tty: true
    ports:
        - "33306:3306"
    environment:
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: orders
      SERVICE_TAGS: prod
      SERVICE_NAME: mysql
      TZ: Asia/Bangkok
    volumes:
      - orders-db:/var/lib/mysql
    networks:
        - app-network
  app:
    build:
      context: .  
      dockerfile: Dockerfile
    image: kodersky/golang-api-example
    container_name: golang-api-example-api
    restart: on-failure
    tty: true
    environment:
      SERVICE_NAME: golang
      SERVICE_TAGS: prod
      TERM: xterm-256color
      TZ: Asia/Bangkok
      WAIT_HOSTS: db:3306
    depends_on:
      - db
    command: sh -c '/wait && /go/src/github.com/kodersky/golang-api-example/main'
    networks:
        - app-network

Golang code:

connection := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", dbUser, dbPass, dbHost, dbPort, dbName)
val := url.Values{}
val.Add("parseTime", "1")
val.Add("loc", "Local")
dsn := fmt.Sprintf("%s?%s", connection, val.Encode())
dbConn, err := sql.Open(`mysql`, dsn)

if err != nil && viper.GetBool("debug") {
    log.Println(err)
}
err = dbConn.Ping()
if err != nil {
    log.Fatal(err)
}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *