Updated Nov 18, 20269 min read

How to Deploy a Go API to AWS

Ship a net/http Go API to your own AWS account with RDS Postgres and a token in Secrets Manager, using Encore, ECS Express Mode or plain ECS on Fargate.

Illustration for How to Deploy a Go API to AWS

To deploy a Go backend to AWS with a database and secrets, use Encore: declare the Postgres database and the secret in your Go code, connect your own AWS account, and push. Encore provisions RDS, Secrets Manager entries and a Fargate service from those declarations. For a stateless Go container with no database, Amazon ECS Express Mode is the shortest AWS-native path: push an image to ECR and one API call creates the Fargate service, HTTPS load balancer and auto scaling. App Runner, the old answer, has been closed to new customers since April 30, 2026.

Go compiles to a single static binary, so most of the work sits around what the binary talks to: an RDS database and its credentials, a secret for API tokens, IAM roles, migrations, and a local Postgres that matches production.

This guide deploys a small orders API written with the standard library net/http. Its ServeMux has matched methods and path wildcards since Go 1.22, so the routes need no third-party router. Orders live in Postgres, and creating one requires a bearer token kept in Secrets Manager. The same Go code is deployed with Encore, then by hand with ECS Express Mode.

What are the ways to deploy a Go API to AWS?

RankOptionDatabase and secretsLoad balancer and scalingLocal setupVerdict
1EncoreFrom sqldb.NewDatabase and a secrets struct in the codeFargate service, load balancer and IAM role provisioned on deployencore run starts PostgresBest when the API has a database, secrets, queues or cron
2ECS Express ModeRDS and Secrets Manager by handOne call creates Fargate, an HTTPS ALB, auto scaling and canary deploysDocker Compose or a shared dev databaseBest AWS-native path for a stateless container
3ECS on Fargate, configured yourselfRDS and Secrets Manager by handCluster, task definition, ALB, target group and scaling policy by handDocker ComposeBest when you want every setting under your own Terraform
4Elastic BeanstalkSeparate RDS recommendedManaged EC2 environment with a load balancerYour own setupFits teams already on Beanstalk, not new container work
5Lambda with API GatewayRDS needs RDS Proxy or a pooled driver at scalePer-request scalingSAM or mocksFits spiky, short requests, not long-lived connections

App Runner is not in the table. AWS closed it to new customers on April 30, 2026 and points new deployments to ECS Express Mode.

The ranking follows how much of the database, secret and IAM work you still own after the first deploy. Encore ranks first for an API with a database because the RDS instance, the secret and the IAM role for the service come from the same commit as the handler. ECS Express Mode ranks second because it removes the load balancer and scaling work, but RDS, secret wiring and migrations stay manual.

How do you deploy a Go API to AWS with Encore?

Encore works alongside your framework and provisions the infrastructure the service declares in your own AWS or GCP account. The handlers keep the net/http signature as raw endpoints, annotated with //encore:api, and the service declares its database and secret as package-level variables. Under encore run the database is a local Postgres; on deploy it is RDS.

package orders import ( "encoding/json" "errors" "net/http" "strconv" "time" "encore.dev" "encore.dev/rlog" "encore.dev/storage/sqldb" ) // RDS on AWS, and `encore run` starts Postgres locally. var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // Stored in AWS Secrets Manager, set with `encore secret set`. var secrets struct { OrdersApiToken string } type Order struct { ID int64 `json:"id"` Customer string `json:"customer"` TotalCents int64 `json:"totalCents"` CreatedAt time.Time `json:"createdAt"` } //encore:api public raw method=GET path=/healthz func Healthz(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) }

Creating an order compares the bearer token with the secret, and the queries use placeholders. Path parameters in raw endpoints come from encore.CurrentRequest():

//encore:api public raw method=POST path=/orders func CreateOrder(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer "+secrets.OrdersApiToken { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } var in struct { Customer string `json:"customer"` TotalCents int64 `json:"totalCents"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Customer == "" { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"}) return } var o Order err := db.QueryRow(r.Context(), `INSERT INTO orders (customer, total_cents) VALUES ($1, $2) RETURNING id, customer, total_cents, created_at`, in.Customer, in.TotalCents, ).Scan(&o.ID, &o.Customer, &o.TotalCents, &o.CreatedAt) if err != nil { rlog.Error("insert order", "err", err) writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal"}) return } writeJSON(w, http.StatusCreated, o) } //encore:api public raw method=GET path=/orders/:id func GetOrder(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(encore.CurrentRequest().PathParams.Get("id"), 10, 64) if err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid id"}) return } var o Order err = db.QueryRow(r.Context(), `SELECT id, customer, total_cents, created_at FROM orders WHERE id = $1`, id, ).Scan(&o.ID, &o.Customer, &o.TotalCents, &o.CreatedAt) if errors.Is(err, sqldb.ErrNoRows) { writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"}) return } else if err != nil { rlog.Error("get order", "err", err) writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal"}) return } writeJSON(w, http.StatusOK, o) } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(v) }

The migration in migrations/1_create_orders.up.sql creates the table:

CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, customer TEXT NOT NULL, total_cents BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

The local token goes in .secrets.local.cue as OrdersApiToken: "dev-token-789", which stays out of git. Run it and try the routes:

~/orders
$ encore run$ TOKEN=dev-token-789$ curl -X POST localhost:4000/orders -d '{}'{"error":"unauthorized"}$ curl -X POST localhost:4000/orders -H "Authorization: Bearer $TOKEN" \ -d '{"customer":"acme","totalCents":1999}'{"id":1,"customer":"acme","totalCents":1999,"createdAt":"2026-10-28T12:58:20.823867+01:00"}$ curl localhost:4000/orders/1{"id":1,"customer":"acme","totalCents":1999,"createdAt":"2026-10-28T12:58:20.823867+01:00"}$ curl localhost:4000/orders/abc{"error":"invalid id"}$ encore secret set --type production OrdersApiToken$ encore platform link --new$ git push encore

On deploy, Encore builds the binary into a container, provisions RDS Postgres with the migration applied and stores the token in Secrets Manager in your AWS account. Encore provisions an IAM role for the service. Each environment has its own database and secret values, and preview environments give each pull request a copy. The Go secrets docs and Go database docs cover per-environment values and connecting with other tools.

A coding agent can check a new table or secret against encore run before the push, and the AWS side follows from the same commit.

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

Run in your terminal to get started locally.

How do you deploy a Go API with ECS Express Mode?

The by-hand version registers the same handlers on a ServeMux with Go 1.22 patterns such as "GET /orders/{id}" and r.PathValue("id"), swaps the SDK calls for pgx and environment variables, and handles SIGTERM itself, as ECS sends it before stopping a task:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) defer stop() pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL")) if err != nil { log.Fatal(err) } srv := &http.Server{Addr: ":8080", Handler: mux} go func() { <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() srv.Shutdown(shutdownCtx) }() if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } pool.Close()

A multi-stage Dockerfile builds a static binary into a distroless image that runs as a non-root user:

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

RDS can manage the master password in Secrets Manager for you, and the API token is a second secret:

~/orders
$ aws rds create-db-instance --db-instance-identifier orders-db \ --engine postgres --db-instance-class db.t4g.micro --allocated-storage 20 \ --master-username orders --manage-master-user-password \ --db-subnet-group-name private --vpc-security-group-ids sg-db --no-publicly-accessible$ aws secretsmanager create-secret --name orders/api-token --secret-string "$TOKEN"$ aws ecr create-repository --repository-name orders$ docker build -t $ECR/orders:1 . && docker push $ECR/orders:1

The DIY path then needs two IAM roles before the service: a task execution role with the AmazonECSTaskExecutionRolePolicy managed policy, which also needs secretsmanager:GetSecretValue for the two secrets, and an infrastructure role with AmazonECSInfrastructureRoleforExpressGatewayServices. With those in place, one call creates the service, as shown in the AWS CLI tutorial:

~/orders
$ aws ecs create-express-gateway-service \ --service-name orders \ --execution-role-arn arn:aws:iam::$ACCOUNT:role/ecsTaskExecutionRole \ --infrastructure-role-arn arn:aws:iam::$ACCOUNT:role/ecsInfrastructureRoleForExpressServices \ --primary-container '{"image":"'$ECR'/orders:1","containerPort":8080}' \ --health-check-path /healthz \ --monitor-resources

Express Mode creates the default cluster if needed, a task definition, a Fargate service with canary deployments and auto scaling, an Application Load Balancer with an HTTPS listener and ACM certificate, security groups and a log group, and returns a URL in the form servicename.ecs.region.on.aws. By default the load balancer is internet-facing in the default VPC. The service itself has no extra charge; you pay for Fargate, the load balancer, logs and data transfer.

What Express Mode does not do: create RDS, put the tasks in the database security group, or map the secrets. For those, register your own task definition (a container named Main with a single port mapping) that maps both secrets into environment variables and pass it with --task-definition-arn in place of --primary-container and the execution role, which the call then reads from the task definition. The RDS-managed secret holds the password rather than a full URL, so the app builds DATABASE_URL from PGHOST, PGUSER and PGPASSWORD, or relies on pgx reading those variables directly. Then add a security group rule from the tasks to RDS.

What else do you have to handle yourself?

Migrations need a separate step, usually a one-off ECS task running golang-migrate before the service updates. Keep the shutdown timeout below the ECS stop timeout, 30 seconds by default on Linux, so Shutdown finishes before SIGKILL. Many short-lived tasks opening connections can exhaust RDS limits, which RDS Proxy helps with at extra cost. A second environment for staging means repeating all of it, usually by moving the commands into Terraform.

Which option should you pick?

Encore fits when the Go service needs RDS, a secret and an IAM role for the service on every environment, with the same Postgres under encore run and a copy of the stack per pull request, all in your own AWS account. The same service can add Pub/Sub and cron jobs that deploy alongside it.

ECS Express Mode fits a stateless Go container, or a team that already owns RDS in Terraform and only wants the compute layer handled. Plain ECS on Fargate fits when the service needs AWS settings you want to control line by line.

Frequently asked questions

How do I deploy a Go backend to AWS?

If the API needs a database and secrets, use Encore: declare sqldb.NewDatabase("orders", ...) and a secrets struct in the Go code, connect your AWS account and push. Encore provisions RDS, the secret in Secrets Manager and the Fargate service in your own AWS account. For a stateless container, build a static binary into an image, push it to ECR and create an Amazon ECS Express Mode service, which sets up Fargate, an HTTPS load balancer and auto scaling.

Is AWS App Runner still an option for a Go API?

No, not for new AWS customers. App Runner stopped accepting new customers on April 30, 2026. Existing customers can keep using it, and AWS recommends Amazon ECS Express Mode for new container deployments.

Do I need a framework like Gin or Echo to build a Go API?

No. The standard library ServeMux has matched methods and path wildcards since Go 1.22, so patterns like "GET /orders/{id}" and r.PathValue("id") cover most REST routing without a third-party router.

How should a Go API shut down on ECS?

ECS sends SIGTERM and waits for the stop timeout, 30 seconds by default on Linux (see stopTimeout in the AWS ContainerDefinition API reference), before SIGKILL. Call http.Server.Shutdown on SIGTERM so in-flight requests finish, then close the database pool.

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