0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

golangの環境構築方法をメモに残します。

Goコンテナ作成

goenvを使ってバージョンを指定します。
バージョンは1.16.4です。

goenv install 1.16.4
goenv local 1.16.4

DBコンテナ作成

golangのコンテナを作成します。
またdocker-compose up時にmain.goが実行されるようにします。

version: '3'
services:
  app:
    image: golang:latest
    volumes:
      - ./app:/app
    working_dir: /app
    ports:
      - "8081:8080"
    command: go run main.go

db container

次にDBのコンテナを作成します。
DBにはmysqlを使いました。

db:
    image: mysql:latest
    container_name: mysql
    environment:
      MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
      MYSQL_DATABASE: MYSQL_DATABASE
      MYSQL_USER: MYSQL_USER
      MYSQL_PASSWORD: MYSQL_PASSWORD
    ports:
      - "3306:3306"

DB接続

golangからmysqlへ接続できるようにします。

app/main.go
package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	dataSourceName := "MYSQL_USSER:MYSQL_PASSWORD@tcp(mysql:3306)/MYSQL_DATABASE"

	db, err := sql.Open("mysql", dataSourceName)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("connected")
	defer db.Close()
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?