Run a Go Gin API on AWS with an Amazon RDS for PostgreSQL database, with Encore provisioning Fargate and RDS in your own AWS account, or by hand with Docker, ECS and the AWS CLI.

The easiest way to deploy a Gin app to AWS with RDS is Encore: you keep your Gin router behind a raw fallback endpoint, declare the Postgres database in Go, and git push deploys the service to Fargate with an Amazon RDS for PostgreSQL database, VPC and secrets provisioned in your own AWS account. If you want to stay on AWS tooling only, ECS Express Mode runs your container behind a load balancer with TLS, and you create RDS, the secret and the network rules yourself. App Runner is no longer an option for new accounts.
Gin builds into one static Go binary, so the code is the easy part of running it on AWS, and the work is around it: a container image and a registry, a Postgres database in private subnets, a password that should never be in the image or the task definition, TLS to the database, a load balancer and security groups that let exactly one thing talk to another.
This guide deploys a small Gin link shortener with a links table on RDS, first with Encore, then by hand with Docker, ECR, RDS and ECS, and ends with when Lambda or Elastic Beanstalk make more sense.
AWS App Runner was the other obvious target, but AWS closed it to new customers on April 30, 2026 and recommends ECS Express Mode instead.
Encore works alongside Gin. The Gin engine keeps every route 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 (Encore 1.58, Gin 1.12)
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, with traces for each request in the local development dashboard.
Encore builds the image and provisions the rest from the code, following its AWS infrastructure docs: 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, and Secrets Manager for credentials injected at runtime. Encore provisions an IAM role for the service. 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, visible 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.
The manual 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. The Gin code is the same router, connected with pgx instead of Encore's sqldb.
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.
// DB_PASSWORD comes from the RDS-managed secret in Secrets Manager.
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=/etc/ssl/rds-global-bundle.pem",
os.Getenv("DB_HOST"), os.Getenv("DB_NAME"), os.Getenv("DB_USER"),
))
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 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.
# 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
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 one key from the RDS-managed 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 RDS rotates the password, running tasks keep the old value until they restart, so plan a forced redeployment after rotation.

Lambda. 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.
Elastic Beanstalk. The Go platform builds and runs your binary on EC2 behind a load balancer. Create RDS separately rather than inside the environment, so the database outlives the environment, and you still own the secret and the network rules.
Verdict. The Gin code barely changes between these options, and the difference is how much AWS you configure around it. ECS Express Mode takes care of the web tier and leaves 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. Start with the quickstart.
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.
Build a container that starts Gin on the PORT environment variable, push it to Amazon ECR, create an RDS for PostgreSQL instance in private subnets with an RDS-managed master password, 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.
Not as a new customer. AWS closed App Runner to new customers on April 30, 2026 and points to ECS Express Mode instead. Existing App Runner customers can keep using it.
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.