LoginSignup
7
3

More than 5 years have passed since last update.

Create an environment for Golang and MySQL using docker-compose.yml

Last updated at Posted at 2019-02-17

Goal

To create an environment for Golang and MySQL, and getting data from database via go application.

Directory Structure

on_your_computer
Docker/
 ├ Go/
 │ └ Dockerfile
 └ MySQL/
   └ Dockefile
   └ test.sql

Create files

docker-compose.yml
version: '3'
services:
  db:
    build:
      context: ./MySQL
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: test_db
      MYSQL_USER: docker
      MYSQL_PASSWORD: docker
    container_name: golang_db
    ports:
      - "3306:3306"
    tty: true
  app:
    build:
      context: ./Go
    volumes:
      - "./Go:/go"
    container_name: golang_app
    ports:
      - "8080:8080"
    tty: true
    depends_on:
      - db
Go/Dockerfile
FROM golang:latest

RUN apt-get update
RUN apt-get install vim -y
RUN go get "github.com/go-sql-driver/mysql"
MySQL/Dockerfile
FROM mysql:5.6
COPY test.sql /docker-entrypoint-initdb.d/test.sql
MySQL/test.sql
Use test_db;

Create table `test_tb` (id int, name varchar(20));

Insert into test_tb (id, name) values (1, 'test-user');

Then run command below

docker-compose up --build

How to use

You can edit main.go at local or docker container (golang_app)

get_into_docker_container
docker exec -it golang_app bash
main.go
package main

import(
        _ "github.com/go-sql-driver/mysql"
        "database/sql"
        "fmt"
        "log"
)

func main() {
        cnn, err := sql.Open("mysql", "docker:docker@tcp(db:3306)/test_db")
        if err != nil {
                log.Fatal(err)
        }

        id := 1
        var name string

        if err := cnn.QueryRow("SELECT name FROM test_tb WHERE id = ? LIMIT 1", id).Scan(&name); err != nil {
                log.Fatal(err)
        }

        fmt.Println(id, name)
}

Build & Run

on_golang_app_container
go run main.go

or

on_your_computer
docker exec -it golang_app bash -c "go run main.go"

you can get line below

1 test-user

Refs

https://github.com/docker-library/mysql/issues/129#issuecomment-178265632
https://hub.docker.com/_/mysql/

7
3
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
7
3