Dockerizing and Live Reloading Go Applications
Introduction
Dockerizing and live reloading Go applications is essential for modern development. This guide will walk you through the process of setting up a Go application, Dockerizing it, and enabling live reloading for efficient development.
Prerequisites
- A Go application
- Docker installed on your machine
- Basic understanding of Go and Docker
Setting Up the Go Application
Initialize a Go module for your application:
go mod init github.com/yourusername/your-go-app
Dockerizing the Go Application
1. Create a Dockerfile
FROM golang:1.23-alpine
WORKDIR /src/app
RUN go install github.com/cosmtrek/air@latest
COPY . .
RUN go mod tidy
2. Create docker-compose.yml
version: "3.9"
services:
app:
tty: true
restart: always
container_name: ticket-booking
build: .
ports:
- "3000:3000"
env_file:
- .env
networks:
- application
depends_on:
db:
condition: service_healthy
volumes:
- .:/src/app
command: air -c .air.toml
db:
image: postgres:alpine
container_name: ticket_booking_db
environment:
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
ports:
- "5432:5432"
volumes:
- postgres-db:/var/lib/postgresql/data
networks:
- application
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
interval: 10s
timeout: 5s
retries: 5
networks:
application:
volumes:
postgres-db:
3. Configure Live Reloading with Air
- Download and copy the sample
.air.tomlfile:curl -o .air.toml https://raw.githubusercontent.com/cosmtrek/air/master/air_example.toml
4. Create a .env File
SERVER_PORT=3000
DB_HOST=db
DB_NAME=ticket_booking
DB_USER=postgres
DB_PASSWORD=postgres
DB_SSLMODE=disable
5. Create config.go
package config
import (
"github.com/caarlos0/env"
"github.com/gofiber/fiber/v2/log"
)
type Config struct {
ServerPort string `env:"SERVER_PORT"`
DBHost string `env:"DB_HOST"`
DBName string `env:"DB_NAME"`
DBUser string `env:"DB_USER"`
DBPassword string `env:"DB_PASSWORD"`
DBSSLMode string `env:"DB_SSLMODE"`
}
func NewEnvConfig() *Config {
cfg := &Config{}
if err := env.Parse(cfg); err != nil {
log.Fatal(err)
}
return cfg
}
6. Create main.go
package main
import (
"github.com/gofiber/fiber/v2"
"yourapp/config"
)
func main() {
cfg := config.NewEnvConfig()
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, Dockerized Go!")
})
app.Listen(":" + cfg.ServerPort)
}
7. Create Makefile
start:
@docker compose up --build
stop:
@docker compose down -v
@docker rmi ticket-booking
Running the Application
Start the application
make start
Stop the application
make stop
Live Reloading
- Run
make start. - Modify your Go code.
- Air will automatically reload the application.
Conclusion
With this setup, your Go application is now Dockerized with live reloading, improving your development workflow and efficiency.