Write down Docker Compose file for Go Lang  and MySQL Application

Write down Docker Compose file for Go Lang and MySQL Application

Here's an example of a Docker Compose file for an easy Go Lang app with a MySQL database. The Go Lang app talks to the MySQL database.

  1. Directory Structure:
/mygolangapp
|-- main.go
|-- Dockerfile
|-- docker-compose.yml
|-- go.mod
|-- go.sum
  1. main.go (Golang Application):
package main

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

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

var db *sql.DB

func main() {
    db, err := sql.Open("mysql", "root:password@tcp(db:3306)/mydatabase")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    router := mux.NewRouter()
    router.HandleFunc("/", helloHandler).Methods("GET")

    log.Println("Server started on :8080")
    log.Fatal(http.ListenAndServe(":8080", router))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query("SELECT message FROM messages")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var message string
    for rows.Next() {
        if err := rows.Scan(&message); err != nil {
            log.Fatal(err)
        }
    }

    fmt.Fprintf(w, "Message from the database: %s\n", message)
}
  1. Dockerfile (GoLang Application):
FROM golang:1.17-alpine AS builder

WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o main .

FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main .
CMD ["./main"]
  1. docker-compose.yml (Docker Compose Configuration):
version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - db
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: mydatabase
    ports:
      - "3306:3306"

Explanation:

  • The app service uses the Dockerfile to set up the GoLang environment and add the application code. It opens port 8080 for the GoLang app to run.

  • The db service gets the official MySQL 8.0 image from Docker Hub. It creates a root password and a database called mydatabase. Port 3306 is opened for MySQL database communication.

  • The depends_on command makes sure the app service starts only when the db service is already running.

To use this setup, create the necessary files and directories as described above. Then, run the following command in the directory containing the docker-compose.yml file:

docker-compose up

This will set up and start both the Go Lang app and the MySQL database. You can access the Go Lang app at http://localhost:8080.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!