In this article, we'll walk through an example of how to set up a Go application with a MySQL database using Docker Compose. This approach simplifies development by managing dependencies and configurations using containers.
Prerequisites
- Basic understanding of Go programming language.
- Docker and Docker Compose installed on your machine.
Step 1: Set Up the Go Application
First, let’s create a simple Go application that will connect to a MySQL database. Start by creating a directory for your project:
mkdir go-docker-example
cd go-docker-exampleCreate a Go module:
go mod init go-docker-exampleNext, create a simple Go application file:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
dsn := "user:password@tcp(mysql:3306)/dbname"
db, err := sql.Open("mysql", dsn)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Connected to MySQL database!")
}This code Example is a very basic Go application that connects to a MySQL database using the Go SQL package and MySQL driver.
Step 2: Create the Docker Compose File
Create a docker-compose.yml file in your project directory:
version: '3.8'
services:
app:
build: .
depends_on:
- mysql
mysql:
image: mysql:latest
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: dbname
MYSQL_USER: user
MYSQL_PASSWORD: password
This YAML configuration defines two services: one for your Go application and another one for MySQL. Ensure to update the credentials as you set in your Go application.
Step 3: Create Dockerfile for Go Application
Create a Dockerfile in the same directory:
FROM golang:1.17 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .
FROM scratch
COPY --from=builder /app/main /
CMD ["/main"]This Dockerfile uses a multi-stage build, optimizing our Go binary for deployment.
Step 4: Building and Running the Application
With docker-compose.yml and the Dockerfile in place, you can now build and run the application:
docker-compose upThis command starts both the Go app and MySQL within separate containers. After it runs successfully, the Go application will connect to the MySQL database as expected.
Conclusion
By following these steps, you can efficiently manage a Go application and a MySQL database using Docker Compose. This setup makes it easier to handle dependencies, and testing across different environments becomes significantly straightforward thanks to containerization.