Table of Contents
Setting up a development environment is crucial for modern web developers. Using Docker with Fiber, a fast HTTP framework for Go, streamlines the process and ensures consistency across different systems. This tutorial provides a comprehensive, step-by-step guide to help developers configure a complete Fiber Docker setup from scratch.
Prerequisites
- Basic knowledge of Docker and Docker Compose
- Go programming language installed on your machine
- Docker Desktop installed and running
- Text editor or IDE of your choice
Step 1: Create Project Directory
Start by creating a new directory for your Fiber project. Open your terminal and run:
mkdir fiber-docker-setup
cd fiber-docker-setup
Step 2: Initialize Go Module
Initialize a new Go module inside your project directory:
go mod init github.com/yourusername/fiber-docker-setup
Step 3: Create Main Application File
Create a file named main.go and add the following code to set up a simple Fiber server:
package main
import (
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, Fiber with Docker!")
})
app.Listen(":3000")
}
Step 4: Create Dockerfile
In the root of your project directory, create a Dockerfile with the following content:
FROM golang:1.20-alpine
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY . .
RUN go build -o main .
EXPOSE 3000
CMD ["./main"]
Step 5: Create Docker Compose File
Create a docker-compose.yml file in your project directory to manage container orchestration:
version: '3.8'
services:
fiber-app:
build: .
ports:
- "3000:3000"
volumes:
- ./:/app
environment:
- GO111MODULE=on
Step 6: Build and Run the Docker Container
Use Docker Compose to build and start your Fiber application:
docker-compose up --build
Once the container is running, open your browser and navigate to http://localhost:3000. You should see the message: Hello, Fiber with Docker!
Additional Tips
- Use
docker-compose downto stop and remove containers. - Mount volumes for live code updates during development.
- Customize your
main.goto add more routes and middleware.
Conclusion
Setting up Fiber with Docker simplifies development and deployment. By following these steps, you create a portable, consistent environment that can be easily shared or deployed to production. Happy coding!