Nov 16, 202611 min read

How to Deploy a Fiber App to AWS

Run a Go Fiber v3 API with Postgres and S3 on AWS: Encore provisions Fargate, RDS and a private bucket in your account from the Go code, compared with ECS Fargate by hand, ECS Express Mode and Lambda.

Illustration for How to Deploy a Fiber App to AWS

A Fiber API compiles to a single Go binary, and that binary is straightforward to put in a container on AWS. A production setup around it is more involved, with a VPC and private subnets, a load balancer, a Fargate service, an RDS database the internet cannot reach, an S3 bucket the service can write to, IAM roles for each, secrets and a pipeline that runs migrations before new tasks start.

This guide deploys a Fiber v3 support-ticket API that stores tickets in Postgres and file attachments in a private S3 bucket. It starts with Encore, which provisions Fargate, RDS and S3 in your own AWS account from the Go code, then covers ECS Fargate by hand, ECS Express Mode and Lambda.

Ways to deploy Fiber to AWS at a glance

EncoreECS Fargate by handECS Express ModeLambda
Infrastructure defined inGo codeTerraform, CDK or consoleECS service settingsSAM, CDK or Terraform
Postgres and S3RDS and S3 provisioned from codeYou create and wire themYou create and wire themYou create them, plus VPC access
Local environmentencore run with Postgres and local object storageDocker ComposeDocker ComposeSAM local or none
DockerfileEncore builds the imageYou write itYou write itZip or image
Runs inYour AWS accountYour AWS accountYour AWS accountYour AWS account

How do you deploy Fiber to AWS with Encore?

Encore

Encore works alongside Fiber, so the routes and handlers you have keep running as Fiber code, and the database and bucket they use are declared in Go next to them. From those declarations Encore knows what to build and provision on each push, and it deploys into your own AWS account, as described in Connect your cloud account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create support-api --example=hello-world$ cd support-api && go get github.com/gofiber/fiber/v3@v3.7.0$ mkdir -p support/migrations

The schema keeps tickets and attachment metadata in Postgres, with the object key as the link to the file in the bucket:

-- support/migrations/1_create_tickets.up.sql CREATE TABLE tickets ( id BIGSERIAL PRIMARY KEY, owner_uid TEXT NOT NULL, email TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open', created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE attachments ( id BIGSERIAL PRIMARY KEY, ticket_id BIGINT NOT NULL REFERENCES tickets(id) ON DELETE CASCADE, object_key TEXT NOT NULL UNIQUE, content_type TEXT NOT NULL, size_bytes BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

The service mounts Fiber with adaptor.FiberApp in a fallback route. Uploads are capped at 10 MiB through Fiber's BodyLimit, which the adaptor enforces with a 413, checked against an allowlist of content types sniffed from the bytes, and written to a private bucket, and reading a ticket returns 15-minute signed download URLs instead of exposing the bucket:

// support/support.go package support import ( "context" "crypto/hmac" "crypto/sha256" "crypto/subtle" "encoding/hex" "errors" "fmt" "net/http" "strconv" "strings" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/storage/objects" "encore.dev/storage/sqldb" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/adaptor" ) // RDS for PostgreSQL on AWS, started locally by `encore run`. var db = sqldb.NewDatabase("support", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // A private S3 bucket on AWS; files are only reachable through signed URLs. var attachments = objects.NewBucket("ticket-attachments", objects.BucketConfig{}) const maxUpload = 10 << 20 // 10 MiB var allowed = map[string]bool{"image/png": true, "image/jpeg": true, "application/pdf": true} var secrets struct { SessionKey string } //encore:authhandler func AuthHandler(ctx context.Context, token string) (auth.UID, error) { uid, err := userIDFromToken(token) if err != nil { return "", &errs.Error{Code: errs.Unauthenticated, Message: "invalid token"} } return uid, nil } // userIDFromToken verifies a signed access token of the form "<id>.<unix-expiry>.<hex hmac>". // In production, verify a JWT against your IdP JWKS (signature, issuer, audience, // expiry) and return the subject. func userIDFromToken(token string) (auth.UID, error) { if secrets.SessionKey == "" { return "", errors.New("auth secret not set") } parts := strings.Split(token, ".") if len(parts) != 3 { return "", errors.New("invalid token") } id, expStr, sig := parts[0], parts[1], parts[2] if id == "" || strings.ContainsAny(id, "/ \t\n") { return "", errors.New("invalid token") } exp, err := strconv.ParseInt(expStr, 10, 64) if err != nil || exp <= time.Now().Unix() { return "", errors.New("invalid token") } mac := hmac.New(sha256.New, []byte(secrets.SessionKey)) mac.Write([]byte(id + "." + expStr)) expected := hex.EncodeToString(mac.Sum(nil)) if subtle.ConstantTimeCompare([]byte(sig), []byte(expected)) != 1 { return "", errors.New("invalid token") } return auth.UID(id), nil } func callerUID() (auth.UID, error) { uid, ok := auth.UserID() if !ok { return "", &errs.Error{Code: errs.Unauthenticated, Message: "unauthenticated"} } return uid, nil } //encore:service type Service struct { handler http.HandlerFunc } func initService() (*Service, error) { app := fiber.New(fiber.Config{BodyLimit: maxUpload}) app.Post("/tickets", createTicket) app.Get("/tickets/:id", getTicket) app.Post("/tickets/:id/attachments", addAttachment) return &Service{handler: adaptor.FiberApp(app)}, nil } //encore:api public raw auth path=/!fallback func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) { s.handler(w, req) } type Ticket struct { ID int64 `json:"id"` Email string `json:"email"` Subject string `json:"subject"` Body string `json:"body"` Status string `json:"status"` Attachments []Attachment `json:"attachments"` } type Attachment struct { ContentType string `json:"content_type"` Size int64 `json:"size_bytes"` URL string `json:"url"` } func createTicket(c fiber.Ctx) error { uid, err := callerUID() if err != nil { return fiber.ErrUnauthorized } var t Ticket if err := c.Bind().Body(&t); err != nil || !strings.Contains(t.Email, "@") || t.Subject == "" { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "email and subject are required"}) } err = db.QueryRow(c.Context(), ` INSERT INTO tickets (owner_uid, email, subject, body) VALUES ($1, $2, $3, $4) RETURNING id, status`, string(uid), t.Email, t.Subject, t.Body).Scan(&t.ID, &t.Status) if err != nil { return err } return c.Status(fiber.StatusCreated).JSON(t) } func addAttachment(c fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { return fiber.ErrNotFound } data := c.Body() ctype := http.DetectContentType(data) if !allowed[ctype] { return c.Status(fiber.StatusUnsupportedMediaType).JSON(fiber.Map{"error": "only PNG, JPEG and PDF files"}) } uid, err := callerUID() if err != nil { return fiber.ErrUnauthorized } ctx := c.Context() var exists bool if err := db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM tickets WHERE id = $1 AND owner_uid = $2)`, id, string(uid)).Scan(&exists); err != nil { return err } if !exists { return fiber.ErrNotFound } key := fmt.Sprintf("tickets/%d/%d", id, time.Now().UnixNano()) w := attachments.Upload(ctx, key, objects.WithUploadAttrs(objects.UploadAttrs{ContentType: ctype})) if _, err := w.Write(data); err != nil { w.Abort(err) return err } if err := w.Close(); err != nil { return err } _, err = db.Exec(ctx, ` INSERT INTO attachments (ticket_id, object_key, content_type, size_bytes) VALUES ($1, $2, $3, $4)`, id, key, ctype, len(data)) if err != nil { // Do not leave an object behind that no row points to. _ = attachments.Remove(ctx, key) return err } return c.SendStatus(fiber.StatusCreated) } func getTicket(c fiber.Ctx) error { uid, err := callerUID() if err != nil { return fiber.ErrUnauthorized } id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { return fiber.ErrNotFound } ctx := c.Context() t := Ticket{Attachments: []Attachment{}} err = db.QueryRow(ctx, `SELECT id, email, subject, body, status FROM tickets WHERE id = $1 AND owner_uid = $2`, id, string(uid)). Scan(&t.ID, &t.Email, &t.Subject, &t.Body, &t.Status) if errors.Is(err, sqldb.ErrNoRows) { return fiber.ErrNotFound } else if err != nil { return err } rows, err := db.Query(ctx, ` SELECT object_key, content_type, size_bytes FROM attachments WHERE ticket_id = $1 ORDER BY id`, id) if err != nil { return err } defer rows.Close() for rows.Next() { var key string var a Attachment if err := rows.Scan(&key, &a.ContentType, &a.Size); err != nil { return err } signed, err := attachments.SignedDownloadURL(ctx, key, objects.WithTTL(15*time.Minute)) if err != nil { return err } a.URL = signed.URL t.Attachments = append(t.Attachments, a) } if err := rows.Err(); err != nil { return err } return c.JSON(t) }

encore run starts Postgres and local object storage and applies the migration, so a fresh clone can create a ticket, attach a PDF and read it back with a working download link. If the attachment row fails to insert after the upload, the handler removes the object, which keeps the bucket from collecting files nothing points to.

Deploy to your AWS account

In the Encore dashboard, go to App Settings > Integrations > Connect Cloud and connect your AWS account, which creates an IAM role Encore uses to provision resources. Create an environment on AWS with Fargate as the compute, then push:

~/support-api
$ git add -A && git commit -m "Fiber support API"$ git push encore

Encore builds the Docker image, pushes it to ECR and provisions a VPC across two availability zones, an Application Load Balancer, the Fargate service in private compute subnets, RDS for PostgreSQL in a private storage subnet and an S3 bucket, as the AWS infrastructure docs describe. Encore provisions an IAM role for the service, gives it its own database role and runs migrations through a proxy inside your environment. Staging and preview environments get the same setup.

When the ticket API later needs to notify an on-call channel, a Pub/Sub topic is one more declaration in the same package, and the next push provisions SNS and SQS. A coding agent working in this repository adds that topic in the same diff as the handler that publishes to it and runs it with encore run first.

Best fit: Fiber APIs that should run on Fargate with RDS and S3 in your own AWS account, with the same database and storage locally and in every environment.

ECS Fargate by hand

The manual route starts with a Dockerfile for Go 1.26 or newer, which Fiber v3 needs, and a multi-stage build keeps the image small and runs the binary as a non-root user on distroless:

FROM golang:1.26 AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /app ./cmd/api FROM gcr.io/distroless/static-debian12:nonroot COPY --from=build /app /app USER nonroot:nonroot EXPOSE 8080 ENTRYPOINT ["/app"]

The infrastructure usually lives in Terraform: a VPC with public and private subnets and NAT gateways, an ECR repository, an ECS cluster, a task definition with an execution role and a task role, a Fargate service, an ALB with a listener, target group and health check path, an RDS instance with its subnet and security groups, an S3 bucket with Block Public Access and a task role policy scoped to its prefix, and the database password in Secrets Manager referenced from the task definition.

A compact task definition for the API container looks like this. The execution role pulls the image and the secret, the task role is what the process uses for S3, and the health check path has to match a Fiber route that does not need a database row, so a cold RDS connection does not fail the load balancer:

{ "family": "fiber-api", "networkMode": "awsvpc", "requiresCompatibilities": ["FARGATE"], "cpu": "512", "memory": "1024", "executionRoleArn": "arn:aws:iam::123456789012:role/fiber-api-execution", "taskRoleArn": "arn:aws:iam::123456789012:role/fiber-api-task", "containerDefinitions": [ { "name": "api", "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/fiber-api:latest", "essential": true, "portMappings": [{ "containerPort": 8080, "protocol": "tcp" }], "secrets": [ { "name": "DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:fiber/database-url" } ], "environment": [ { "name": "ATTACHMENTS_BUCKET", "value": "fiber-ticket-attachments" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/fiber-api", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "api" } } } ] }

The Fiber app reads DATABASE_URL and ATTACHMENTS_BUCKET from the environment and uses the AWS SDK for uploads and presigned URLs. The task role policy should allow s3:PutObject, s3:GetObject and s3:DeleteObject on arn:aws:s3:::fiber-ticket-attachments/* only. CI builds the image, pushes it to ECR, runs migrations from a one-off Fargate task in the same private subnets, then registers a new task definition revision and updates the service. The migration task uses the same image with a migrate command, so two API replicas do not race AutoMigrate or a startup hook.

Best fit: platform teams with existing ECS modules who want every setting in their own Terraform.

ECS Express Mode

ECS Express Mode creates a Fargate service, load balancer, scaling and HTTPS endpoint from a container image and a few settings, and AWS points App Runner users to it now that App Runner no longer accepts new customers. You still write the Dockerfile and push to ECR, and Express Mode covers compute only, so the RDS instance, the bucket, the task role policy and the secrets are yours to create and connect.

Best fit: a single containerized Fiber service that needs a quick Fargate deployment and already has its data stores.

Lambda

The Fiber adapter in aws-lambda-go-api-proxy is built for Fiber v2. A v3 app can still run on Lambda by converting it with adaptor.FiberApp(app) and passing that handler to the project's httpadapter, which accepts any net/http handler. It costs nothing at idle and scales with requests, but reaching RDS means running the function in the VPC, and connection counts usually call for RDS Proxy. Lambda's payload quotas also cap request bodies below the 10 MiB this API accepts, so attachments would go straight to S3 through presigned URLs instead.

Best fit: low or spiky traffic Fiber APIs with light database use and small request bodies.

How to choose

Pick Encore when you want a Fiber API with Postgres and file storage running on Fargate, RDS and S3 in your own AWS account, with the infrastructure coming from the Go code and the same setup locally. Build ECS by hand when the team already maintains ECS in Terraform. ECS Express Mode suits a single container that already has its data stores, and Lambda suits spiky traffic with light database use.

Frequently asked questions

How do I deploy a Fiber app to AWS?

Build the app into a container image, push it to ECR and run it as an ECS Fargate service behind an Application Load Balancer, with RDS and any S3 buckets in the same VPC and account. The image needs Go 1.26 or newer for Fiber v3, should run as a non-root user and listen on the port the target group health check uses.

How do I deploy a Fiber app to AWS with Encore?

Mount the Fiber app in a raw endpoint with //encore:api public raw path=/!fallback through adaptor.FiberApp, declare the database with sqldb.NewDatabase and the bucket with objects.NewBucket, connect your AWS account in the Encore dashboard, create an AWS environment with Fargate and run git push encore. Encore builds the image and provisions Fargate, RDS for PostgreSQL and S3 in your account.

Can I run Fiber v3 on AWS Lambda?

The Fiber adapter in aws-lambda-go-api-proxy targets Fiber v2. For v3, convert the app to a net/http handler with adaptor.FiberApp and wrap it with the project's httpadapter, then put API Gateway or a function URL in front of it.

Does App Runner still work for a new Fiber app?

App Runner no longer accepts new customers, and AWS points new container workloads to ECS Express Mode, which creates a Fargate service, load balancer and HTTPS endpoint from an image.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders