Torihaji's Growth Diary

Little by little, no hurry.

docker compose で MySQLを立ち上げる(ちょっとGo)

はじめに

現在、Goを触っています。

そこでgorm?とか使うためにMySQLを使うらしいのですが、

Udemyがローカルに入れたものを使っていました。

せっかくならDockerで立てたものを使いたくね?てことで急遽やりました。

この前PostgreSQLのコンテナ立てたしいけるでしょ、という楽観的思考のもと今ノリで書いてます。

いけるかな。

やり方

  1. 公式を読む。

https://hub.docker.com/_/mysql

これを読みます。

  1. docker-compose.ymlを作る。

公式のをパクります。

# Use root/example as user/password credentials
version: '3.1'

services:

  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
    # (this is just an example, not intended to be a production configuration)

あとは必要な以下の情報をちょろっと。

version: '3.1'

services:

  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_USER: example
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql


volumes:
  mysql_data:

立ち上げ

docker compose upで立ち上がるのを確認

接続

docker compose exec db bashで一旦コンソールへ入る。

次はmysqlコマンドで接続

bash-5.1# mysql -h localhost -P 3306 -u root -p
Enter password: 

パスワードはさっき入れたexample。

これで繋がりました。

この後の話のために

CREATE USER 'notes'@'localhost' IDENTIFIED BY 'tmp_pwd';
CREATE DATABASE notes;
GRANT ALL PRIVILEGES ON notes.* TO 'notes'@'localhost';

だけやっておきます。(udemyのまんまですね)

SHOW DATABASES;で作成したデータベース一覧を見れます。(psqlよりわかりやすかった)

おまけ

で今回やりたいことはgormに繋げること。

と言うことで色々入れます。

作業時のディレクトリ構造はこんなです。

go mod とかした状態です。

で、ライブラリを入れる。

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

次は接続用関数を作る

var DB *gorm.DB

func connectDatabase() {
    dsn := "notes:tmp_pwd@tcp(localhost:3306)/notes?charset=utf8"
    databse, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("Failed to connect to database!")
    }

    DB = databse
}

でmain.goはこんな感じ。

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

var DB *gorm.DB

func connectDatabase() {
    dsn := "notes:tmp_pwd@tcp(localhost:3306)/notes?charset=utf8"
    databse, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        fmt.Println("error:", err)
        panic("Failed to connect to database!")
    }

    DB = databse
}

func main(){
    r := gin.Default()
    r.Use(gin.Logger())

    r.Static("/vendor", "./static/vendor")

    r.LoadHTMLGlob("templates/**/*")

    connectDatabase()

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "views/index.html", gin.H{
            "title": "Notes Application",
        })
    })

    log.Println("Server Started!")
    r.Run() //Defailt Port 8080
}

えー繋がりません。

なんでだ。パスワードあってるじゃん。

Access denied for user 'notes'@'172.18.0.1' (using password: YES)

格闘の結果、AIにも聞いた結果。

CREATE USER 'notes'@'localhost' IDENTIFIED BY 'tmp_pwd';

userの作り方が不味かったみたい。

CREATE USER 'notes'@'%' IDENTIFIED BY 'tmp_pwd';

とすることで"任意のipからユーザ名notesでパスワードがtmp_pwdで接続してきたuserはok"となるらしい。

うまく説明できませんが、多分下記の記事が原因かと。dockerの知識が不足してた。

Dockerのネットワーク、基礎理解は万全ですか?【Dockerコンテナ・グレートジャーニー④】 #container - Qiita

とりあえずこれで繋がりました

終わりに

すぐ終わると思ったのに。

疲れた。寝る。