Skip to main content

Kubernetes Example

Github StackBlitz

This project demonstrates how to deploy a Go application using the Fiber framework on a Kubernetes cluster.

Prerequisites

Ensure you have the following installed:

  • Golang
  • Fiber package
  • Docker
  • Kubernetes
  • kubectl
  • Minikube (for local development)

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/k8s
  2. Install dependencies:

    go get
  3. Build the Docker image:

    docker build -t fiber-k8s-example .
  4. Start Minikube (if using Minikube):

    minikube start
  5. Deploy the application to Kubernetes:

    kubectl apply -f my-service.yaml

Running the Application

  1. Check the status of the pods:

    kubectl get pods
  2. Forward the port to access the application:

    kubectl port-forward svc/fiber-k8s-example 3000:3000
  3. Access the application at http://localhost:3000.

Example

Here is an example main.go file for the Fiber application:

package main

import (
"context"
"log"
"os/signal"
"syscall"

"github.com/gofiber/fiber/v3"
)

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

app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, Kubernetes!")
})

app.Get("/healthz", func(c fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
})

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

go func() {
if err := app.Listen(":3000"); err != nil {
log.Printf("Listen error: %v\n", err)
}
}()

<-ctx.Done()
log.Println("Gracefully shutting down...")
if err := app.ShutdownWithContext(ctx); err != nil {
log.Printf("Shutdown error: %v\n", err)
}
}

Here is an example Dockerfile for the application:

FROM golang:1.25-alpine AS builder

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /fiber-k8s-example

EXPOSE 3000

CMD ["/fiber-k8s-example"]

Here is an example my-service.yaml file for deploying the application to Kubernetes:

apiVersion: apps/v1
kind: Deployment
metadata:
name: fiber-k8s-example
spec:
replicas: 2
selector:
matchLabels:
app: fiber-k8s-example
template:
metadata:
labels:
app: fiber-k8s-example
spec:
containers:
- name: fiber-k8s-example
image: fiber-k8s-example:latest
ports:
- containerPort: 3000
readinessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 10
periodSeconds: 20
---
apiVersion: v1
kind: Service
metadata:
name: fiber-k8s-example
spec:
type: NodePort
selector:
app: fiber-k8s-example
ports:
- protocol: TCP
port: 3000
targetPort: 3000
nodePort: 30001

References