As the title says.
Here has the same symptoms. I corrected the MySQL connection information as I was told, and it was fixed. Below is Before / After.
Before
docker-compose.yml
version: "3"
services:
app:
build: .
depends_on:
- db
volumes:
- ./:/go/src/app
ports:
- 3000:3000
environment:
MYSQL_DATABASE: go_app_dev
MYSQL_USER: docker
MYSQL_PASSWORD: password
db:
image: mysql:5.7
container_name: dockerMySQL
volumes:
- ./storage/mysql_data:/var/lib/mysql
ports:
- 3306:3306
environment:
MYSQL_DATABASE: go_app_dev
MYSQL_USER: docker
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
db/db.go
package db
import (
"fmt"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var (
db *gorm.DB
err error
)
func Init() {
user = os.Getenv("MySQL_USER")
pass = os.Getenv("MYSQL_PASSWORD")
dbname := os.Getenv("MYSQL_DATABASE")
connection := fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", user, pass, dbname)
db, err := gorm.Open("mysql", connection)
if err != nil {
panic(err)
}
}
After
docker-compose.yml
version: "3"
services:
app:
build: .
depends_on:
- db
volumes:
- ./:/go/src/app
ports:
- 3000:3000
environment:
MYSQL_DATABASE: go_app_dev
MYSQL_HOST: dockerMySQL #add to!!
MYSQL_USER: docker
MYSQL_PASSWORD: password
db:
image: mysql:5.7
container_name: dockerMySQL #add to!!
volumes:
- ./storage/mysql_data:/var/lib/mysql
ports:
- 3306:3306
environment:
MYSQL_DATABASE: go_app_dev
MYSQL_USER: docker
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
db/db.go
// ...Abbreviation
func Init() {
user = os.Getenv("MySQL_USER")
pass = os.Getenv("MYSQL_PASSWORD")
host = os.Getenv("MYSQL_HOST") //Here!!
dbname := os.Getenv("MYSQL_DATABASE")
connection := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, pass, host, dbname) //Fix!!
db, err := gorm.Open("mysql", connection)
if err != nil {
panic(err)
}
}
The deciding factor was that when specifying the connection information with the second argument of gorm.Open, ** connect with the container name of the Docker container running MySQL **. The reason I couldn't connect to MySQL with the Before code in the first place was because MySQL wasn't listening on localhost or TCP port 3306. And since the containers running with docker-compose communicate via the docker network, it is possible to connect with the container name instead of the network name, and the app container with the connection information as posted in After It seems that you can connect to the db container from. I'm not sure if this kind of understanding is correct, but w
Recommended Posts