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:
|-- main.go
|-- Dockerfile
|-- docker-compose.yml
|-- go.mod
|-- go.sum
  1. main.go (Golang Application):
package main

import (

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

var db *sql.DB

func main() {
    db, err := sql.Open("mysql", "root:password@tcp(db:3306)/mydatabase")
    if err != nil {
    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 {
    defer rows.Close()

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

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

COPY . .
RUN go mod download
RUN go build -o main .

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


  • 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!