Deploying a Go Fiber application to Fly

Bjorn Krolsavatar

Bjorn Krols

Published on
28 April 2022

In this tutorial you will learn how to deploy a containerized Go Fiber application to Fly.

The final code of this article can be found here.

Prerequisites

  • A Fly account
  • A computer with Go, Docker, and Flyctl (the Fly CLI)

Creating the application

go mod init hello-world
go get github.com/gofiber/fiber/v2

./src/application.go

package main

import (
"github.com/gofiber/fiber/v2"
"log"
"math/rand"
"strconv"
)

const port = 8080

func main() {
    application := fiber.New()

    application.Get("/", func(c *fiber.Ctx) error {
        return c.JSON(&fiber.Map{
            "message": "Hello, World!",
        })
    })

    application.Get("/random", func(c *fiber.Ctx) error {
        return c.JSON(&fiber.Map{
            "number": rand.Intn(10),
        })
    })

    log.Fatalln(application.Listen(":" + strconv.Itoa(port)))
}

To run the application locally:

go run ./src/application.go

Containerizing the application

Dockerfile

FROM golang:1.18-alpine
WORKDIR /usr/src/app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY ./src ./src
RUN go build -o ./bin/hello-world ./src
EXPOSE 8080
CMD [ "./bin/hello-world" ]

To build and run the container locally:

docker build . -t hello-world
docker run -dp 8080:8080 hello-world

Deploying the application

  1. fly launch to prepare your fly.toml file, containing your project settings. Inside the fly.toml file, ensure the service's internal_port (8080 by default) matches the port exposed by your container.
  2. fly deploy to deploy your application.
  3. fly open to open the deployed application in your browser.

Cleaning up

fly destroy your-unique-app-id -y removes your application from the Fly platform.

That's all! Don't forget to delete the application once you're done testing.

The final code of this article can be found here.

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this