Run a Gin API on AWS with Amazon RDS for PostgreSQL: with Encore in your own AWS account, on Elastic Beanstalk, or by hand on ECS Fargate, with the code and commands for each.

The easiest way to deploy a Gin app to AWS with RDS is Encore. Your Gin router keeps every route, the Postgres database is one declaration in code, and git push provisions Fargate, Amazon RDS for PostgreSQL and the VPC in your own AWS account.
If you would rather stay on AWS tooling, Elastic Beanstalk and ECS Express Mode both run Gin well, but the database, its password and the network rules are yours to set up.
AWS App Runner used to be the obvious sixth row, but AWS has closed it to new customers and recommends ECS Express Mode instead.
Every option below deploys the same small Gin link shortener with a links table on RDS, so you can compare how much AWS each one leaves to you.
Encore works alongside Gin: the Gin engine keeps its routes and sits behind a raw fallback route, and the database is a package-level declaration next to the handlers that use it. Locally, encore run starts a Postgres database for it. On AWS, Encore provisions Amazon RDS for PostgreSQL in your own account, along with the VPC, the Fargate service and the load balancer.
Run in your terminal to get started locally.
The first migration creates the table:
-- links/migrations/1_links.up.sql
CREATE TABLE links (
id BIGSERIAL PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
target_url TEXT NOT NULL,
clicks BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// links/links.go (Gin 1.12, Encore CLI 1.58)
package links
import (
"errors"
"net/http"
"net/url"
"encore.dev/storage/sqldb"
"github.com/gin-gonic/gin"
)
// Amazon RDS for PostgreSQL on AWS, a local Postgres with `encore run`.
var db = sqldb.NewDatabase("links", sqldb.DatabaseConfig{
Migrations: "./migrations",
})
//encore:service
type Service struct {
router *gin.Engine
}
func initService() (*Service, error) {
r := gin.New()
r.Use(gin.Recovery())
r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusOK) })
r.POST("/links", createLink)
r.GET("/l/:slug", followLink)
return &Service{router: r}, nil
}
// Every request that does not match another Encore endpoint goes to Gin.
//
//encore:api public raw path=/!fallback
func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) {
s.router.ServeHTTP(w, req)
}
type createReq struct {
Slug string `json:"slug" binding:"required,alphanum,max=32"`
URL string `json:"url" binding:"required,url"`
}
func createLink(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<16)
var req createReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if u, err := url.Parse(req.URL); err != nil || (u.Scheme != "https" && u.Scheme != "http") {
c.JSON(http.StatusBadRequest, gin.H{"error": "url must be http or https"})
return
}
var id int64
err := db.QueryRow(c.Request.Context(), `
INSERT INTO links (slug, target_url) VALUES ($1, $2)
ON CONFLICT (slug) DO NOTHING
RETURNING id`, req.Slug, req.URL).Scan(&id)
if errors.Is(err, sqldb.ErrNoRows) {
c.JSON(http.StatusConflict, gin.H{"error": "slug taken"})
return
} else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not save link"})
return
}
c.JSON(http.StatusCreated, gin.H{"id": id, "slug": req.Slug})
}
func followLink(c *gin.Context) {
var target string
err := db.QueryRow(c.Request.Context(), `
UPDATE links SET clicks = clicks + 1
WHERE slug = $1
RETURNING target_url`, c.Param("slug")).Scan(&target)
if errors.Is(err, sqldb.ErrNoRows) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
} else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
c.Redirect(http.StatusFound, target)
}
The code has no connection string: db is already connected to the right database in each environment, locally and on AWS, and ON CONFLICT (slug) DO NOTHING turns a duplicate slug into a 409 instead of a 500.
Run it locally with encore run. Encore starts Postgres in Docker, applies the migration and serves the Gin routes on localhost:4000, and the local development dashboard shows a trace for each request.
Encore builds the image and provisions the rest from the code, as its AWS infrastructure docs describe: a VPC across two availability zones with the containers in private compute subnets, an Application Load Balancer, a Fargate service, an RDS for PostgreSQL database in an isolated storage subnet, and Secrets Manager for credentials injected at runtime. Migrations in links/migrations are applied before the new code starts, so keep each schema change compatible with the code that is still running. Every resource lives in your account and shows up in the AWS console like anything else you own.
Adding infrastructure later is another declaration in the same package: a cache becomes ElastiCache, a Pub/Sub topic becomes SNS and SQS, and a secret is set with encore secret set and lands in Secrets Manager. That also suits AI coding agents: when an agent adds a cache to a Gin handler, the infrastructure change is in the same diff you review, and it can try the result with encore run before anything touches AWS.
Elastic Beanstalk is what most AWS tutorials reach for first, and for one Gin binary it works: the Go platform builds your code on the instance, runs it behind nginx, and adds a load balancer, scaling and health checks. RDS, the database password and migrations stay with you. The Gin code drops Encore's sqldb and connects with pgx, using the same router.
RDS for PostgreSQL 15 and later rejects connections without SSL by default (rds.force_ssl is on), so connect with sslmode=verify-full and the RDS CA bundle:
// internal/app/db.go (pgx 5.13)
package app
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
// NewPool connects to RDS with TLS verified against the RDS CA bundle
// at RDS_CA_FILE.
// DB_PASSWORD is injected from Secrets Manager by the platform.
func NewPool(ctx context.Context) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(fmt.Sprintf(
"host=%s port=5432 dbname=%s user=%s sslmode=verify-full sslrootcert=%s",
os.Getenv("DB_HOST"), os.Getenv("DB_NAME"), os.Getenv("DB_USER"), os.Getenv("RDS_CA_FILE"),
))
if err != nil {
return nil, err
}
cfg.ConnConfig.Password = os.Getenv("DB_PASSWORD")
cfg.MaxConns = 10
return pgxpool.NewWithConfig(ctx, cfg)
}
Size MaxConns against the database: ten instances or tasks with ten connections each is 100 connections, and a small RDS instance class has a low max_connections, so size the pool against the instance, not against the traffic you hope for.
Beanstalk's nginx forwards to the port in the PORT environment property and uses 5000 when it is not set, so read it instead of hard-coding Gin's default :8080:
// cmd/server/main.go (Gin 1.12, pgx 5.13)
package main
import (
"context"
"log"
"os"
"example.com/links-api/internal/app"
)
func main() {
pool, err := app.NewPool(context.Background())
if err != nil {
log.Fatal(err)
}
defer pool.Close()
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
// app.NewRouter registers the same /links and /l/:slug handlers,
// with pool.QueryRow in place of Encore's db.QueryRow.
log.Fatal(app.NewRouter(pool).Run(":" + port))
}
The Buildfile builds the binary on the instance and the Procfile starts it. The first Procfile entry has to be called web:
# Buildfile make: go build -o bin/application ./cmd/server # Procfile web: bin/application
Put the RDS CA bundle in certs/ and set the rest in .ebextensions. On platform versions released since March 26, 2025, Beanstalk can load a Secrets Manager secret into an environment variable when an instance boots, so the password never sits in your source bundle:
# .ebextensions/options.config
option_settings:
aws:elasticbeanstalk:application:environment:
GIN_MODE: release
DB_HOST: links-db.abc123xyz.eu-west-1.rds.amazonaws.com
DB_NAME: links
DB_USER: links_app
RDS_CA_FILE: /var/app/current/certs/rds-global-bundle.pem
aws:elasticbeanstalk:application:environmentsecrets:
DB_PASSWORD: arn:aws:secretsmanager:eu-west-1:123456789012:secret:links-app-db-password-AbCd12
DB_PASSWORD points at a plain-text secret that holds the password of a links_app role with access to the links schema only. The environment's EC2 instance profile needs secretsmanager:GetSecretValue on it, and when you rotate the password you have to restart the app servers to pick up the new value.
Pick a Go platform branch whose Go version is at least the one in your go.mod, or the build on the instance fails. eb create --database can create RDS inside the environment, but that ties the database's lifecycle to the environment, so terminating or rebuilding the environment can take the database with it. Create the RDS instance on its own (the aws rds create-db-instance command in the ECS section below works unchanged), allow port 5432 from the environment's instance security group, and run migrations from CI or a one-off task, since Beanstalk will not apply them for you.
The container route has four parts: an image in ECR, an RDS instance, the database password in Secrets Manager, and a Fargate service that can reach the database. It reuses NewPool and cmd/server from the Beanstalk section, so the only change is the image.
# Dockerfile
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
ADD https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /out/rds-global-bundle.pem
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
COPY --from=build /out/rds-global-bundle.pem /etc/ssl/rds-global-bundle.pem
ENV GIN_MODE=release PORT=8080 RDS_CA_FILE=/etc/ssl/rds-global-bundle.pem
EXPOSE 8080
ENTRYPOINT ["/server"]
Push it to an ECR repository with docker build, aws ecr get-login-password | docker login and docker push, then point the service at the image URI.
Create the instance in private subnets, with no public access, and let RDS generate and store the master password in Secrets Manager with --manage-master-user-password:
aws rds create-db-instance \ --db-instance-identifier links-db \ --engine postgres \ --db-instance-class db.t4g.micro \ --allocated-storage 20 \ --db-name links \ --master-username app \ --manage-master-user-password \ --db-subnet-group-name links-private \ --vpc-security-group-ids sg-0db0000000000000 \ --no-publicly-accessible
The database security group should allow port 5432 from the service's security group only. Use the RDS-managed master secret only for initial setup and migrations, from a one-off ECS task or a CI step with network access to the VPC; nothing in this setup applies them for you. Create a separate database role with only the privileges the API needs on the links schema, store that role's password in its own Secrets Manager secret, and inject that secret into the running task. Keep the master secret out of the service task definition.
ECS Express Mode is the shortest path: give it the image, a task execution role and an infrastructure role, and it creates a Fargate service with a URL, a load balancer with TLS and autoscaling. If you need to control every piece, write the task definition, service, target group and listener yourself in Terraform or CDK.
Either way, the password reaches the container through the task definition's secrets block, which reads the password key from the links_app role's secret (ECS docs):
{
"environment": [
{ "name": "DB_HOST", "value": "links-db.abc123xyz.eu-west-1.rds.amazonaws.com" },
{ "name": "DB_NAME", "value": "links" },
{ "name": "DB_USER", "value": "links_app" }
],
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:links-app-db:password::"
}
]
}
The task execution role needs secretsmanager:GetSecretValue on that secret (and kms:Decrypt if it uses a customer managed key). When that password rotates, running tasks keep the old value until they restart, so plan a forced redeployment after rotation.

The aws-lambda-go-api-proxy Gin adapter (ginadapter.NewV2 for HTTP API and function URL events) lets the same router run as a function, which fits APIs with long idle periods. To reach RDS, the function has to run in your VPC, and each execution environment opens its own connections, which is why AWS recommends RDS Proxy in front of the database. The password should be read from Secrets Manager when the function starts, not stored in its environment variables.
Lambda suits a webhook receiver or an internal API that sits idle most of the day, less so a busy API that keeps a warm connection pool.
Verdict: the Gin code barely changes between these options, and what changes is how much AWS you configure around it. Elastic Beanstalk and ECS Express Mode take care of the web tier and leave the database, the secret, TLS to RDS, migrations and the network rules to you. Encore ranks first because it provisions all of those in your own AWS account from one sqldb.NewDatabase line and a git push, and the same code runs locally against a local Postgres database, so start with the quickstart.
Use Encore. Mount the Gin engine in a raw fallback endpoint, declare the database with sqldb.NewDatabase, connect your AWS account in the Encore dashboard and run git push encore. Encore builds the image and provisions Fargate, Amazon RDS for PostgreSQL, the VPC and the secrets in your own AWS account, and applies your migrations before the new code starts.
Yes. The Elastic Beanstalk Go platform builds your app from a Buildfile, starts it from a Procfile and puts nginx in front of it on the port in the PORT variable (5000 by default). Create the RDS for PostgreSQL instance outside the environment so it outlives the environment, open port 5432 from the environment's security group, and pass the password in through Beanstalk's Secrets Manager environment secrets.
Build a container that starts Gin on the PORT variable, push it to Amazon ECR, create an RDS for PostgreSQL instance in private subnets, and run the container on ECS Fargate, either through ECS Express Mode or with your own task definition, service and load balancer. Inject the database password from Secrets Manager into the task and allow the task security group to reach the database on port 5432.
Yes. The aws-lambda-go-api-proxy library has a Gin adapter that turns API Gateway or function URL events into requests for your Gin engine. To reach RDS the function has to run in your VPC, and each execution environment opens its own connections, so AWS recommends RDS Proxy for connection pooling.
No. AWS closed App Runner to new customers and points them to ECS Express Mode. Existing App Runner customers can keep using it.
Build Go backends without the infrastructure boilerplate
Encore gives you type-safe APIs, local Postgres and Pub/Sub out of the box, built-in distributed tracing, and automated deploys to your own AWS or GCP account.