How to Set Up an Application Load Balancer in AWS: CLI Checklist
Export PDF
Print-friendly layout with a copyright watermark; choose Save as PDF in the print dialog

TL;DR
- The path is fixed: internet → ALB security group on 443 → listener → rule → target group → registered targets. Almost every "the ALB is down" ticket breaks at the last hop, not at the ALB.
- Your health-check path must return a plain
200with no auth, no redirect, and no database dependency. A301on/healthcan drain a target group to zero healthy hosts in about 60 seconds. - Defaults cost you time: healthy threshold 5 × 30s interval = 150 seconds before a new target serves traffic, and the 300-second deregistration delay makes every deploy feel stuck. Change both on day one.
Pre-flight: what has to exist before the first API call
The ALB wizard will happily let you create something broken, so collect these first. It's five minutes of prep that saves an hour of ValidationError loops.
- A VPC with at least two subnets in different Availability Zones (three is better for SMB production). AWS recommends
/27or larger per ALB subnet and 8+ free IPs, because the load balancer scales by consuming ENAs and IPs in each AZ. - A process listening on a known port — say
8080for a Node/Express app,80for nginx — bound to0.0.0.0, not127.0.0.1. - A
/healthzroute that returns200and does not touch the database. - An ACM certificate in the same region as the ALB. This one bit me: a
us-east-1certificate referenced from aneu-west-1ALB fails withCertificateNotFound. If you also front the site with CloudFront, you end up with two certificates for the same domain, one per region, and both must be renewed. - A DNS plan: a Route 53 alias record (free queries, no CNAME at the zone apex) or a CNAME if DNS lives elsewhere.
For the checks below I'll use us-east-1, a VPC vpc-0a1b2c3d4e5f67890, and two private subnets in us-east-1a/us-east-1b.
推荐
推荐服务 · 一站式办理
由云市场认证服务商承接,下单后按需沟通交付。
腾讯云市场
NGINX / APACHE / TOMCAT / IIS 证书配置 · SSL证书安装
各服务器环境 SSL 证书安装配置,教程看不懂?直接交给服务商办。
查看服务 →
阿里云市场
代购 SSL 证书 · DigiCert / GeoTrust / RapidSSL 单域名 DV
单域名 DV 证书代购,主流品牌可选,比官网渠道更省。
查看服务 →
阿里云市场
Wildcard 通配符 SSL 证书安装部署续费申请
一张通配符保护全部一级子域名,含安装部署与续费服务。
查看服务 →
腾讯云市场
SSL证书申请+配置 · 宝塔/WDCP 面板全站加密(OV 企业单域名等规格)
付费证书云上签发、一键部署到宝塔/WDCP 站点,OV 企业单域名可选。
查看服务 →
阿里云市场
企业级 EV / OV 证书与代码、驱动签名服务
SSL EV/OV 证书 + 软件代码签名、驱动签名,企业级一站式办理。
查看服务 →
阿里云市场
GlobalSign 代码签名证书服务(OV/EV 企业版)
对 exe/dll/驱动等软件做数字签名,消除「未知发布者」警告,企业版含申请代办。
查看服务 →
阿里云市场
HTTPS证书申请 · SSL证书安装部署 · 证书续费
证书过期、部署报错、需要续期?申请+部署+续费一站式办理。
查看服务 →
云市场服务直达
阿里云市场
腾讯云市场
华为云商店
Minimal working config in five CLI steps
Create the target group first — you can't attach a listener to something that doesn't exist yet.
export TG_ARN=$(aws elbv2 create-target-group
--name app-tg-http
--protocol HTTP --port 8080
--vpc-id vpc-0a1b2c3d4e5f67890
--target-type ip
--health-check-path /healthz
--health-check-interval-seconds 15
--health-check-timeout-seconds 5
--healthy-threshold-count 2
--unhealthy-threshold-count 3
--matcher HttpCode=200
--region us-east-1
--query 'TargetGroups[0].TargetGroupArn' --output text)
Use `--target-type ip` for Fargate, EKS, or anything on-prem via Direct Connect; use `instance` for plain EC2 so targets are registered by instance ID. Mixing them up produces a target group that accepts registrations and never passes a health check.
The load balancer itself needs the subnets, not the instances:
```bash
export ALB_ARN=$(aws elbv2 create-load-balancer
--name app-alb
--subnets subnet-0aaa1111 subnet-0bbb2222
--security-groups sg-0albsecuritygrp
--scheme internet-facing
--type application
--ip-address-type ipv4
--region us-east-1
--query 'LoadBalancers[0].LoadBalancerArn' --output text)
It comes up in `provisioning` state and flips to `active` in roughly 2–3 minutes. Poll with `aws elbv2 describe-load-balancers --names app-alb --query 'LoadBalancers[0].State.Code'`.
Two security groups, referencing each other by ID rather than CIDR. This is the detail people skip and then spend an evening on:
```bash
# Public edge: 80/443 from the world to the ALB SG
aws ec2 authorize-security-group-ingress --group-id sg-0albsecuritygrp
--protocol tcp --port 443 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id sg-0albsecuritygrp
--protocol tcp --port 80 --cidr 0.0.0.0/0
# App SG: accept only from the ALB SG, on the app port
aws ec2 authorize-security-group-ingress --group-id sg-0appsecuritygrp
--protocol tcp --port 8080 --source-group sg-0albsecuritygrp
Now the listeners. HTTP gets a redirect, HTTPS terminates TLS and forwards:
```bash
aws elbv2 create-listener --load-balancer-arn $ALB_ARN
--protocol HTTP --port 80
--default-actions '[{"Type":"redirect","RedirectConfig":{"Protocol":"HTTPS","Port":"443","StatusCode":"HTTP_301"}}]'
export LISTENER_ARN=$(aws elbv2 create-listener --load-balancer-arn $ALB_ARN
--protocol HTTPS --port 443
--certificates CertificateArn=arn:aws:acm:us-east-1:111122223333:certificate/abc-123
--ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06
--default-actions '[{"Type":"forward","TargetGroupArn":"'$TG_ARN'"}]'
--query 'Listeners[0].ListenerArn' --output text)
Finally register targets and point DNS at the ALB name:
```bash
aws elbv2 register-targets --target-group-arn $TG_ARN
--targets Id=10.0.2.44,Port=8080 Id=10.0.3.61,Port=8080
aws elbv2 describe-load-balancers --names app-alb
--query 'LoadBalancers[0].DNSName' --output text
# app-alb-1234567890.us-east-1.elb.amazonaws.com
## Parameter-by-parameter: defaults vs what I change
Most of the console defaults are tuned for "don't surprise anyone", not for "deploy on Friday". These are the values I set for a typical SMB web app.
| Setting | AWS default | What I set | Why |
|---|---|---|---|
| Health check path | `/` | `/healthz` | `/` often renders a template or hits the DB; you want a static 200 |
| Interval / timeout | 30s / 5s | 15s / 5s | Faster recovery; keep timeout well under interval |
| Healthy threshold | 5 | 2 | 5 × 30s = 150s before a new target serves traffic |
| Unhealthy threshold | 2 | 3 | Tolerates one blip without flapping |
| Matcher | `200` | `200` | Never widen to `200-399`; it hides redirect bugs |
| Deregistration delay | 300s | 30s | Every ECS deploy otherwise idles for 5 minutes |
| Idle timeout | 60s | 60s (120s if long-polling) | Requests silently dropped at 60s produce `504`s that look random |
| Cross-zone LB | on | on | Free on ALB; keeps targets evenly used across AZs |
| Slow start | off | 30s | Gives a cold JVM/Node process time before it takes full load |
Two more that aren't in the table because they're situational: enable **access logs** to S3 before you need them (you can't backfill), and turn on **desync mitigation** in `defensive` mode only if you have clients sending malformed `Content-Length` headers — `strictest` will reject them with a 400.
## Verify it, then roll back safely
Health first. If this doesn't say `healthy`, nothing downstream matters:
```bash
aws elbv2 describe-target-health --target-group-arn $TG_ARN
--query 'TargetHealthDescriptions[].{Id:Target.Id,Port:Target.Port,State:TargetHealth.State,Reason:TargetHealth.Reason}'
--output table
Then hit the endpoint through the ALB, not around it:
```bash
curl -sS -o /dev/null -w '%{http_code} %{time_total}sn' https://app.example.com/healthz
# 200 0.042s
Rollback is a single API call if you kept the previous target group alive. Point the listener back:
```bash
aws elbv2 modify-listener --listener-arn $LISTENER_ARN
--default-actions Type=forward,TargetGroupArn=$OLD_TG_ARN
Better than a hard switch: two target groups behind one rule with weights, so 10% of traffic goes to the new build. `--default-actions '[{"Type":"forward","ForwardConfig":{"TargetGroups":[{"TargetGroupArn":"'$OLD_TG'","Weight":90},{"TargetGroupArn":"'$NEW_TG'","Weight":10}]}}]'` — no DNS change, no waiting for TTLs.
## The 23:40 page: a 301 health check knocked out the whole target group
On 2025-11-18 at 23:40 UTC, PagerDuty fired `UnHealthyHostCount >= 1` on a production ALB in `us-east-1`. Six ECS tasks registered, healthy host count dropping roughly one every 30 seconds. The CloudWatch metric showed 503s climbing while CPU on the tasks sat at 4%.
The target group console line read:
Health checks failed with these codes: [301]
The first config was the obvious one: path `/health`, protocol HTTP, matcher `200`, registered port `8080`. It had worked for months because the `/health` route used to return `200{}` directly. The week before, a middleware change added a global HTTPS redirect — `app.use((req,res,next) => req.secure ? next() : res.redirect(301, 'https://' + req.headers.host + req.url))` — mounted *above* the health route. Now the ALB's plain-HTTP probe got a `301` to `https://10.0.2.44:8080/health`, which the matcher correctly rejected.
I did not widen the matcher to `200-399`. A 301-to-anywhere would mark the target healthy while proving nothing about the app, and the next real failure would be masked the same way. Instead I mounted a dedicated route before the redirect middleware:
```javascript
app.get('/healthz', (req, res) => res.status(200).send('ok'));
and updated the target group with `--health-check-path /healthz`. Verification was two-sided: `describe-target-health` returned all six targets `healthy` within 90 seconds, and from a bastion I confirmed the target answered directly — `curl -i http://10.0.2.44:8080/healthz` → `HTTP/1.1 200 OK` — so I knew the fix was the route and not the security group or the port.
The related symptom is worth memorising: if access logs show `elb_status_code 502` with `target_status_code "-"`, the ALB never received a response at all — wrong port, app bound to `127.0.0.1`, or the target SG is missing the ALB source rule. A 503 with `target_status_code "-"` usually means zero healthy targets.
## When NOT to use an Application Load Balancer
ALB is Layer 7 only. If your service speaks MySQL, MQTT, raw TCP, or you need a static IP per AZ that partners can allowlist, that's NLB — it's cheaper at low throughput and gives you Elastic IPs.
Skip the ALB entirely for a single-instance side project with under a few thousand requests a day: an EC2 instance with Caddy or nginx doing TLS in front of the app costs less than the ALB's hourly base charge, which dominates at low request rates (LCU pricing only starts to matter past a few hundred requests per second). The catch is you own cert renewal and failover.
| Need | ALB | NLB |
|---|---|---|
| HTTP routing by path/host/header | Yes, up to 100 rules | No |
| WebSocket / HTTP/2 / gRPC | Yes | Partial (TCP passthrough) |
| Static IP or EIP | No (DNS name only) | Yes |
| Non-HTTP protocols | No | Yes |
| Source IP preserved to target | Via `X-Forwarded-For` | Yes, natively |
## Quick reference cheat sheet
| Task | Command |
|---|---|
| Get ALB DNS name | `aws elbv2 describe-load-balancers --names app-alb --query '
Leave a Reply