Gofiber is a fast lightweight web framework with simple api, inspired by expressjs. The simplicity of the api makes it easy to get started with. It’s also fast and has a lot of features.

Setup

Create a new project

Create a new directory and initialize a go module.

go mod init github.com/adharshmk96/gofiber-init

Install gofiber

go get -u github.com/gofiber/fiber/v2

a main.go with hello world

touch main.go
package main

import "github.com/gofiber/fiber/v2"

func main() {
    // gofiber with default settings
    app := fiber.New()

    // handler for root path
    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World πŸ‘‹!")
    })

    // start server on port 3000
    app.Listen(":3000")
    fmt.Println("Server started on port 3000")
}

Dockerfile for building the app

touch Dockerfile
# Start from the latest golang base image
FROM golang:latest as builder

# Add maintainer info
LABEL maintainer="dev@adharsh.in"

# Set the current working directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. They will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the working directory inside the container
COPY . .

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app-binary .

######## Start a new stage from scratch #######
FROM alpine:latest

RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the Pre-built binary file from the previous stage. Observe we also copied the .env file
COPY --from=builder /app/app-binary .

# Command to run the executable
CMD ["./app-binary"]

I use a docker compose file for additional convenience

touch docker-compose.yml
services:
  myapp:
    image: myapp
    container_name: myapp
    build:
      context: .
      dockerfile: Dockerfile

Now I can run the app with

go run .

Build the docker image

docker compose build myapp

Run the docker image

docker compose up myapp

There you go, a simple gofiber server running in docker. with few steps.

The final directory structure looks like this

.
β”œβ”€ Dockerfile
β”œβ”€ docker-compose.yml
β”œβ”€ go.mod
β”œβ”€ go.sum
└─ main.go