AWSBeginner
ALB 502 or 503? Every target is unhealthy, yet the site still returns 200

Key results
- Both targets go unhealthy after a new release, yet all 4 requests still return 200: the load balancer "fails open" and sends to every target.
- Stop the app process (port 8080 closed, the target answers with a TCP RST): the user gets 502 Bad Gateway, not 503.
- Deregister every target: the target group is empty, and only now does the user get 503 Service Unavailable.
- Find the real cause: app v2 moved its health endpoint to /healthz; changing exactly 1 health check line makes both targets healthy again.
- Learn to read the error in order: HTTP code, state and reason of each target, then the health check path against the path the app really answers 200 on.
What you need
- No prior load balancer knowledge: the guide explains everything from scratch.
- A Linux machine with Docker and Docker Compose (tested on Debian 12, Docker 29, Compose v5). Setup is in the "Lab setup" guide.
- No AWS account needed. A real ALB is billed by the hour, so the lab uses Envoy (an open-source load balancer) configured to answer like an ALB; every difference from an ALB is spelled out.
- Time
- 30 min
- Cost
- $0, runs on your own machine
- Application Load Balancer
- Target group
- Envoy
- Docker Compose
- AWS CLI
Watch the lab video

🎬 Goes live 06 Feb 2027, 20:00 (UTC+7)
“The site returns 502” and “the site returns 503” are the two most common incidents for an application behind a load balancer. Many people assume: “the targets are unhealthy, so the load balancer returns 503”. The AWS Application Load Balancer (ALB) does not do that. When every target is unhealthy, the ALB still sends requests to all of them, and users may still get 200.
This guide builds a real “ALB” on your own machine (Envoy configured to answer like an ALB), puts two web apps behind it as targets, then causes one incident at a time: a release that moves the health endpoint, a dead app, deregistered targets. Each time, we measure which code the user gets. At the end we change exactly one line of configuration and everything is healthy again.
A few terms first
- Load balancer
- A machine in front of several servers. It takes user requests and shares them among the servers behind it.Example: An ALB takes requests on port 80/443 and shares them between 2 web servers.
- Target and target group
- A target is one machine (or container) that receives requests from the load balancer. A target group is the list of targets doing the same job, plus how to check their health.Example: Target group "web" holds app1 and app2 on port 8080.
- Health check
- The load balancer calls a path on every target at a fixed interval. The right code (usually 200) enough times in a row means healthy; failing enough times means unhealthy.Example: GET /health every 2 seconds.
- Fail open
- When no target is healthy, the load balancer does not block everything; it sends requests to every target, whatever its health.Example: Both targets unhealthy, requests still reach app1 and app2.
- 502 Bad Gateway
- The load balancer has a target to send to, but the target answers badly: it refuses the connection (TCP RST), closes it mid-way, or sends an invalid response.Example: The app process died, port 8080 is closed.
- 503 Service Unavailable
- For an ALB: there is no target to send to, for example the target group has no registered targets.Example: All targets deregistered during maintenance.
The lab model and how it works
Everything runs on one Linux machine with Docker, from one Docker Compose file. The two web apps are real and answer for real. The “ALB” is Envoy, an open-source load balancer (a CNCF project), tuned to behave like an ALB in the places this guide measures.
Component diagram
What each component is
| Component | What it is | Role on real AWS | Built with / file |
|---|---|---|---|
alb (Envoy v1.40.2) |
Load balancer listening on 127.0.0.1:8080 |
Application Load Balancer: listener + target group + health check | envoy/envoy.yaml |
tg |
Envoy cluster; its target list is read from a file | Target group | envoy/eds/tg.yaml |
app1, app2 (python 3.13) |
Small web app answering hello from appN vN |
EC2 instances or ECS tasks running the app | app/app.py, app/chay.sh |
trang-thai/ |
Folder holding each app’s version (v1/v2) and “down” flag |
Deployments and app failures | created and changed by lab.sh |
lab.sh |
Shortcuts: goi, suc-khoe, trien-khai, sap, song-lai, huy-dang-ky, dang-ky, sua-health-check |
Stand-ins for curl and aws elbv2 ... |
source lab.sh |
The shortcut names are Vietnamese: goi = call, suc-khoe = health, trien-khai = deploy, sap = crash, song-lai = revive, huy-dang-ky = deregister, dang-ky = register, sua-health-check = fix the health check.
How the components connect
The three containers share the Docker network 172.30.11.0/24: alb at .2, app1 at .11, app2 at .12. Only alb publishes ports to the host, and only on 127.0.0.1 (8080 for users, 9901 for Envoy’s admin page).
- The user calls
http://127.0.0.1:8080/. - Envoy picks a healthy target in target group
tgand forwards the request to that target’s port 8080. - In parallel, every 2 seconds Envoy calls
GET /healthon each target. Two 200s in a row make a target healthy; two failures make it unhealthy. - If no target is healthy, Envoy sends to every target (fail open). If the target group is empty, Envoy itself returns 503.
What is prepared
11-alb-502-503/├── docker-compose.yml # 3 containers: app1, app2, alb (Envoy)├── app/│ ├── app.py # web app: v1 healthy at /health, v2 moves it to /healthz│ └── chay.sh # keeps the app running; a "sap" file stops the process├── envoy/│ ├── envoy.yaml # Envoy playing the ALB│ ├── eds/tg.yaml # current target list (Envoy watches this folder)│ ├── tg-2-target.yaml # 2-target version (register)│ └── tg-rong.yaml # 0-target version (deregister)├── lab.sh # shortcuts├── dung.sh # build and wait for 2 healthy targets└── don.sh # remove everything| Part | Real or simulated | Notes |
|---|---|---|
| Web app, TCP connections, HTTP codes | Real | Real requests through a real load balancer |
| Load balancer | Envoy instead of an ALB | 5 settings changed to match the ALB (table in step 6) |
| Register / deregister targets | Swap the target list file | On AWS: aws elbv2 register-targets / deregister-targets |
| Health check timing | Shortened | 2 seconds instead of the ALB default of 30 |
The overall run
| # | Action | Expected result |
|---|---|---|
| 1 | Build, call it while everything is normal | 2 healthy targets, 200s shared between them |
| 2 | Roll out v2 (health endpoint moves) | 2 unhealthy targets, yet still 200 |
| 3 | Stop the app process | 502 Bad Gateway |
| 4 | Start the app again, deregister every target | 503 Service Unavailable |
| 5 | Register again, fix 1 health check line | 2 healthy targets, 200 |
| 6 | Read how Envoy was tuned to match the ALB | Know where the lab differs from a real ALB |
| 7 | Clean up | Containers and state folder removed |
Configuration files
docker-compose.yml
name: l11services: app1: image: python:3.13-alpine container_name: l11-app1 command: ["sh", "/app/chay.sh"] environment: [TEN=app1] volumes: ["./app:/app:ro", "./trang-thai/app1:/trang-thai"] networks: {lab: {ipv4_address: 172.30.11.11}} app2: # same as app1, TEN=app2, IP 172.30.11.12 alb: image: envoyproxy/envoy:v1.40.2 container_name: l11-alb command: ["envoy", "-c", "/etc/envoy/envoy.yaml", "--log-level", "warn"] volumes: ["./envoy:/etc/envoy"] ports: ["127.0.0.1:8080:8080", "127.0.0.1:9901:9901"] networks: {lab: {ipv4_address: 172.30.11.2}}networks: lab: ipam: {config: [{subnet: 172.30.11.0/24}]}| Line | Meaning | Why it is set this way |
|---|---|---|
image: python:3.13-alpine, envoyproxy/envoy:v1.40.2 |
Pinned image versions | Repeatable results; a new latest can change behaviour. |
./app:/app:ro |
App code mounted read-only | Both apps share one codebase; :ro so the container cannot change it. |
./trang-thai/app1:/trang-thai |
One state folder per app | lab.sh writes the version and the “down” flag here; the app reads them, no rebuild needed. |
ipv4_address: 172.30.11.11 |
Fixed IP per target | Envoy’s target list holds IPs, like an ALB target group of type ip. |
ports: ["127.0.0.1:8080:8080", ...] |
Ports published on 127.0.0.1 only | Only the lab machine can call it. Without 127.0.0.1, Docker publishes on every network card. |
9901 |
Envoy’s admin page | suc-khoe reads target state here. It has no password, so never expose it. |
envoy/envoy.yaml (the important part)
route_config: virtual_hosts: - name: all domains: ["*"] routes: [{match: {prefix: "/"}, route: {cluster: tg, timeout: 10s}}] local_reply_config: mappers: - filter: {response_flag_filter: {flags: ["UF"]}} # target sent a TCP RST status_code: 502 # ALB: 502 Bad Gateway body: {inline_string: "Bad Gateway"} - filter: {response_flag_filter: {flags: ["UH"]}} # no target to send to status_code: 503 # ALB: 503 Service Unavailable body: {inline_string: "Service Unavailable"} clusters: - name: tg # ~ target group type: EDS # targets come from envoy/eds/tg.yaml connect_timeout: 10s # ALB: no connection within 10 s = 504 eds_cluster_config: eds_config: path_config_source: path: /etc/envoy/eds/tg.yaml watched_directory: {path: /etc/envoy/eds} ignore_health_on_host_removal: true common_lb_config: healthy_panic_threshold: {value: 1} # 0 healthy: send to ALL (~ ALB fail open) health_checks: - timeout: 2s interval: 2s # ALB default 30 s no_traffic_interval: 2s unhealthy_threshold: 2 # ALB default 2 healthy_threshold: 2 # ALB default 5 http_health_check: path: /health| Line | Meaning | Why it is set this way |
|---|---|---|
routes: [{match: {prefix: "/"}, route: {cluster: tg}}] |
Every path goes to target group tg |
Like an ALB listener with a single default rule “forward to target group”. |
local_reply_config flag UF → 502 |
When the connection to the target is refused, answer 502 | Envoy answers 503 here by default; an ALB answers 502. Changed so the codes match. |
flag UH → 503 |
When there is no target to send to, answer 503 | Same as an ALB with an empty target group. |
type: EDS, watched_directory |
Envoy reads the target list from a file and reloads it when the file changes | Stands in for register-targets / deregister-targets: swap the file to register or deregister. |
connect_timeout: 10s |
Wait up to 10 seconds to connect to a target | The ALB also waits 10 seconds; after that it returns 504. |
ignore_health_on_host_removal: true |
A target removed from the list is dropped at once | Envoy keeps it until its health check fails by default; an ALB drops a deregistered target. |
healthy_panic_threshold: {value: 1} |
Below 1% healthy (that is, 0) send to all | Envoy “panics” below 50% healthy by default; an ALB fails open only when every target is unhealthy. |
interval: 2s, healthy_threshold: 2 |
Check every 2 seconds, 2 passes make healthy | Shortened to see results in seconds. ALB defaults: 30 seconds and 5 passes. |
no_traffic_interval: 2s |
Keep checking even with no requests | Envoy slows to 60 seconds with no traffic by default; an ALB checks steadily. |
path: /health |
Health check path | This is the line we will fix. |
app/app.py
def do_GET(self): pb = phien_ban() # "v1" or "v2", read from /trang-thai duong_suc_khoe = "/health" if pb == "v1" else "/healthz" if self.path in ("/health", "/healthz"): ma, noi_dung = (200, "ok") if self.path == duong_suc_khoe else (404, "not found") else: ma, noi_dung = 200, f"hello from {TEN} {pb}"| Line | Meaning | Why it is set this way |
|---|---|---|
phien_ban() |
Reads the version from /trang-thai/phien-ban |
“Deploying” a new version just writes v2 to a file, no image rebuild. |
"/health" if pb == "v1" else "/healthz" |
v1 is healthy at /health, v2 moves it to /healthz |
Simulates a very common mistake: a release moves the health endpoint and nobody updates the target group. |
(404, "not found") |
The wrong health path returns 404 | The old path is gone, as in real life: the health check gets 404 and marks the target unhealthy. |
200, f"hello from {TEN} {pb}" |
Every other path returns 200 with the app name and version | You can see which app and which version served each request. |
app/chay.sh
while true; do if [ -f /trang-thai/sap ]; then sleep 1; continue; fi python -u /app/app.py & P=$! while kill -0 $P 2>/dev/null; do [ -f /trang-thai/sap ] && kill $P && break sleep 0.5 done wait $P 2>/dev/nulldone| Line | Meaning | Why it is set this way |
|---|---|---|
[ -f /trang-thai/sap ] |
If the sap file exists, do not run the app |
Creates a “dead process” incident: the container lives, but nothing listens on port 8080. |
kill $P |
If the app is running and sap appears, stop it |
Port 8080 closes; new connections are refused with a TCP RST. |
while true |
Delete sap and the app starts again |
song-lai only has to delete the file. |
Step 1: Build and call it while everything is normal
What you are doing: start 3 containers, wait for 2 healthy targets, then call the “ALB” 4 times.
cd 11-alb-502-503 && ./dung.sh && source lab.shsuc-khoe; goi 4| Line | Meaning | Why it is set this way |
|---|---|---|
./dung.sh |
Writes v1 for both apps, copies the 2-target list into eds/tg.yaml, runs docker compose up -d, waits until Envoy reports 2 healthy targets |
Calling before targets are healthy gives different results and is easy to misread. |
source lab.sh |
Loads the shortcuts into the shell | source keeps the functions in your shell. |
suc-khoe |
Reads Envoy’s /clusters page and prints each target’s IP and state |
Like aws elbv2 describe-target-health. |
goi 4 |
Calls http://127.0.0.1:8080/ 4 times, prints the HTTP code and body |
Like a user opening the page 4 times. |

How to read it:
- Two
healthylines: both targets answer 200 on/health. - Four
200 hello from ...lines: requests are shared betweenapp1andapp2. This is the state to return to at the end.
Step 2: Roll out v2 and guess the code
What you are doing: “deploy” v2 to both apps. v2 moves its health endpoint from /health to /healthz, but the target group still checks /health. Before running it, guess: will the user get 200, 502 or 503?
trien-khai v2; sleep 5; suc-khoe; goi 4| Line | Meaning | Why it is set this way |
|---|---|---|
trien-khai v2 |
Writes v2 to both apps’ version files |
Like a pipeline deploying the new version to every target at once. |
sleep 5 |
Wait 5 seconds | Enough for 2 failed health checks (2 × 2 seconds) to mark the targets unhealthy. |

How to read it:
- Two targets
unhealthy (/failed_active_hc): the health check calls/health, v2 answers 404, so both are marked failed. - Yet all 4 requests return
200 hello from ... v2. With no healthy target left, the load balancer fails open and sends to every target. The app works fine, so it answers 200. - This is the key signal of the guide: unhealthy + users still get 200 = the health check is wrong, not the app. On AWS the target reason would be
Target.ResponseCodeMismatch(the health check got a code other than the expected one).
Step 3: Stop the app process
What you are doing: kill the app process on both targets so port 8080 closes. The containers keep running. Guess first: which code?
sap; sleep 4; suc-khoe; goi 3| Line | Meaning | Why it is set this way |
|---|---|---|
sap |
Creates the sap file in app1’s and app2’s state folders |
chay.sh sees it and stops the app: like a crash or running out of memory. |
sleep 4 |
Wait 4 seconds | Let the app stop fully and the health check notice. |

How to read it:
- Target state is exactly the same as step 2: two
unhealthylines. - But the user gets
502 Bad Gateway. The load balancer still fails open and sends to the targets; nothing listens on port 8080, so the target refuses the connection with a TCP RST. An ALB that gets a TCP RST while connecting returns 502. - The lesson: the unhealthy state does not decide the error code. The code depends on how the target answers when traffic fails open to it: working app gives 200, refused connection gives 502, no connection within 10 seconds gives 504.
Step 4: Start the app again, deregister every target
What you are doing: let the apps run again, then remove both targets from the target group (like maintenance, or an Auto Scaling group scaling to 0). Guess first: which code?
song-lai; huy-dang-ky; sleep 2; suc-khoe; goi 3| Line | Meaning | Why it is set this way |
|---|---|---|
song-lai |
Deletes the sap file, the app runs again |
To make sure the 503 is not caused by a dead app. |
huy-dang-ky |
Copies tg-rong.yaml (0 targets) over eds/tg.yaml |
Envoy watches the folder and reloads at once. Like aws elbv2 deregister-targets. Written to a temp file then mv, so Envoy never reads a half-written file. |

How to read it:
target group: 0 target: nothing left to send to.- The user gets
503 Service Unavailable, returned by the load balancer itself; the request reaches no app. The apps are running fine, but nobody sends them requests. - For an ALB, 503 means “nowhere to send”: the target group has no registered targets, or every target is in the
unusedstate (for example a stopped EC2 instance, or a target in an Availability Zone the load balancer does not use).
Step 5: Register again and fix exactly 1 line
What you are doing: register the 2 targets again, see which path the health check uses, then change it to /healthz to match v2.
dang-ky; health-pathsua-health-check; sleep 5; suc-khoe; goi 4| Line | Meaning | Why it is set this way |
|---|---|---|
dang-ky |
Copies the 2-target list into eds/tg.yaml |
Like aws elbv2 register-targets. |
health-path |
grep -n 'path: /health' envoy/envoy.yaml |
Shows the current health check path and its line number. On AWS: aws elbv2 describe-target-groups --query 'TargetGroups[].HealthCheckPath'. |
sua-health-check |
sed changes path: /health to path: /healthz, then restarts the alb container |
The only change. Envoy reads its config file on start. |
sleep 5 |
Wait 5 seconds | Enough for 2 passing health checks to make the targets healthy. |

How to read it:
- Line 52 changes from
path: /healthtopath: /healthz. - Both targets
healthy, requests return200 hello from app1 v2. The app did not change at all; only the health check configuration did. - In this capture all 4 requests hit
app1: right after Envoy restarts, whichever target turns healthy first gets the traffic first. Call a few more times andapp2shows up too.
On real AWS, the fix is one command:
aws elbv2 modify-target-group \ --target-group-arn <target-group-ARN> \ --health-check-path /healthz| Line | Meaning | Why it is set this way |
|---|---|---|
modify-target-group |
Changes the target group settings | The health check belongs to the target group, not to the load balancer or the listener. |
--health-check-path /healthz |
Changes the health check path | The one change needed; no app redeploy. |
Step 6: How Envoy was tuned to match an ALB
What you are doing: print the configuration lines that make Envoy behave like an ALB.
grep -nE 'status_code|flags|panic|path: /h' envoy/envoy.yaml| Line | Meaning | Why it is set this way |
|---|---|---|
grep -nE '...' |
Prints only the lines with return codes, failure flags, the panic threshold and the health check path, with line numbers | Puts the 4 key differences on one screen. |

| Behaviour | Envoy default | Lab setting | ALB |
|---|---|---|---|
| No healthy target left | Sends to all below 50% healthy | healthy_panic_threshold: 1 (only at 0% healthy) |
Fails open when every target is unhealthy |
| Target refuses the connection | 503 | flag UF → 502 |
502 |
| No target | 503 | flag UH → 503 |
503 |
| Health check with no traffic | Every 60 seconds | no_traffic_interval: 2s |
Checks steadily |
| Target deregistered | Kept until its health check fails | ignore_health_on_host_removal: true |
Dropped (after the deregistration delay) |
Where the lab differs from a real ALB: no deregistration delay (an ALB waits 300 seconds by default for in-flight requests before dropping a target); no 504 measured (it needs a target that hangs for more than 10 seconds); shorter health check timing.
Taking it to production
- Read the error in order. (1) The HTTP code users get. (2)
aws elbv2 describe-target-health: each target’s state and reason (Target.ResponseCodeMismatch,Target.Timeout,Target.FailedHealthChecks…). (3) Compare the target group’sHealthCheckPathwith the path the app really answers 200 on. These three steps usually find the cause in minutes. - Pair the code with the target state. Unhealthy + 200: the health check is wrong. Unhealthy + 502: the app is dead, listens on the wrong port, or the target’s security group / firewall blocks the load balancer. 503: empty target group or targets in the
unusedstate. 504: the target accepts connections slowly or hangs. - Change the health path BEFORE the release. When a new version moves the health endpoint: update the target group first, or let the app answer 200 on both paths for one transition release. Do not deploy first and fix later.
- Do not rely on fail open. It keeps the site up when the health check is wrong, but it also hides the problem: nobody notices the broken health check until a real incident. Alarm on the number of healthy targets.
Applying it on real AWS
- ALB health check defaults: path
/, every 30 seconds (5 to 300 allowed), 5-second timeout, 5 passes for healthy, 2 failures for unhealthy, expected code200. Change them withaws elbv2 modify-target-group(--health-check-path,--health-check-interval-seconds,--matcher HttpCode=200). - CloudWatch: alarm on the target group’s
HealthyHostCount(below the number of targets you expect) andUnHealthyHostCount; addHTTPCode_ELB_502_CountandHTTPCode_ELB_503_Countto see when the load balancer itself returns errors. - Target group health: the Target group health requirements setting (a minimum count or percentage of healthy targets) makes the ALB fail open earlier, for example below 50% healthy, instead of waiting for 0%. No setting turns fail open off completely.
- ALB access logs:
request_processing_time,target_processing_timeandresponse_processing_timeequal to-1mean the ALB could not send the request to a target (often seen with 502s).
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| Targets unhealthy, users still get 200 | Wrong health check path, port or expected code | Compare HealthCheckPath / Matcher with the app; fix the target group. |
| Targets unhealthy, users get 502 | App dead, listening on the wrong port, or the target’s security group does not let the load balancer in | Check the app process, the port, and the security group (allow the ALB’s security group). |
| 503 while the app is fine | No registered targets, or targets in an Availability Zone the load balancer does not use | describe-target-health; register targets, enable the right AZs on the load balancer. |
| 504 Gateway Timeout | The target does not accept a connection within 10 seconds, or takes longer than the idle timeout | Check target load, network ACLs, idle timeout. |
dung.sh prints “Chua san sang” (not ready) |
Images still downloading, or another program already uses port 8080 | docker compose logs alb; stop whatever holds port 8080. |
suc-khoe prints nothing after the fix |
Envoy is still restarting | Wait a few seconds and run it again. |
Clean up
./don.shFAQ
If every target is unhealthy, the ALB returns 503, right? No. The ALB fails open and sends to every target. Users get whatever the target answers (200 if the app still works, 502 if the target refuses the connection).
When does an ALB return 503?
When there is nowhere to send: the target group has no registered targets, or every target is in the unused state.
What is the difference between 502 and 503? 502: there is a target, but it answers badly (refused connection, closed connection, invalid response). 503: there is no target to send to.
Should the health check use /?
It can, but the home page is often heavy (database calls, rendering). A dedicated path such as /health is light, fast, and checks only what the app needs to serve users.
References
- AWS: Health checks for Application Load Balancer target groups
- AWS: Troubleshoot your Application Load Balancers
- AWS: Edit target group attributes (target group health)
- AWS re:Post: How do I troubleshoot Application Load Balancer HTTP 502 errors?
- AWS re:Post: How do I troubleshoot 504 errors with an Application Load Balancer?
- Envoy: Panic threshold
- Envoy: Local reply modification

Cloud & Network Engineer · TrungCLN
Designs and runs AWS infrastructure, hybrid networking (VPN, BGP) and cloud security. Every guide on this site is built and run for real before it is written.
Related guides
AWSBeginner35 minutes
IAM AccessDenied with the right action: S3 ARNs, explicit Deny and roles
Your policy allows s3:GetObject, yet you get AccessDenied? A hands-on IAM lab with real authorization: bucket vs object ARNs, Deny beats Allow, STS roles.
AWSBeginner45 min
Private subnet can't reach the Internet: route tables, NAT Gateway and VPC endpoints
A host in a private subnet cannot reach the Internet? Build a real lab with route tables, NAT and internet gateways, an S3 gateway endpoint, and price NAT at real rates.