0

I have made a REST API using Golang and it connects to MySQL DB present on MySQL Workbench installed locally, now I wish to dockerise this API but how do I connect to external DB in Docker-Compose? I'm new to docker, so have little idea of things.

func dbConnection() (db *sql.DB) {
    db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/testDB")
    if err != nil {
        panic(err)
    }
    return db
} 

1 Answers1

0

You have to change localhost with the docker.host as I explained here https://stackoverflow.com/a/61001152/418599 .

In other words you should write a docker build script which set an environment variable by:

IP_ADDRESS=$(ip addr show | grep "\binet\b.*\bdocker0\b" | awk '{print $2}' | cut -d '/' -f 1)

Then use docker-compse to build the image passing the above ip address as follow:

extra_hosts:
  docker.host: ${IP_ADDRESS}

And finally address inside your GO sources the IP_ADDRESS environment variable in place of localhost.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74