GO project: Gorm connect with mysql docker

Self Learning Programmer ๐ง๐ผโ๐ป
How to use a docker container as a MySQL service for a GO project? How to connect with MySQL docker container?
In this blog, we are discussing how to use MySQL container as a service in a go project with the gorm package.
Below is a docker-compose file which will create a MySQL container. Save it as docker-compose.yaml file.
version: '3'
services:
mysql_db:
image: mysql:latest
restart: always
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: 123
MYSQL_ROOT_HOST: '%'
phpmyadmin:
image: phpmyadmin/phpmyadmin:5.0.2
restart: always
ports:
- 9001:80
environment:
PMA_HOST: mysql_db
depends_on:
- mysql_db
Run docker-compose up -d to start containers.
In the above example, you can access PhpMyAdmin at http://localhost:9001. Login to the account using username: root and password: 123.
Sample GO program to connect with MySQL service is shown below. Copy and paste the code into the main.go named file.
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct{
gorm.Model
Name string `json:"name"`
}
var db *gorm.DB
var err error
func main() {
db, err = gorm.Open("mysql","root:123@tcp(0.0.0.0:3306)/sample?charset=utf8&parseTime=True")
if err != nil{
panic(err)
}else{
fmt.Println("Connected DB")
}
}
Run the above code if you get the print statement Connected DB you have successfully connected your GO project with MySQL docker container.
Note:
Don't forget to create 'sample' database in MySQL. You can use PhpMyAdmin for creating it.
Before running the above GO file you should get all the packages you have imported.


