Application Load Balancer returns 502 for a Node.js target
HTTP 502: Bad gatewayShort answer
An ALB returns 502 when the target gives it something it cannot use: a refused or reset connection, a connection closed mid-request, a bad response, or a header over 32 K. For Node.js the most common cause is that Node.js closes idle connections sooner than the ALB expects. Raise the keep-alive timeout above the ALB idle timeout.
Fix it fast
1Find out which cause you have
Check the target response from the instance itself, bypassing the load balancer. If this works, the problem is between the ALB and Node.js, not in the app code.
curl -i http://127.0.0.1:3000/health2Match what you see, then jump to its fix
- 1
502 now and then, under normal traffic, with the app healthyThe target closes the connection sooner than the ALB idle timeoutFix - 2
502 on every request, and the target is unhealthy or never took a connectionTraffic from the ALB to the target port is blocked or refusedFix - 3
502 on specific routes, often for signed-in users with large cookiesThe response is malformed or the header block is over 32 KFix - 4
502 on every request after the target group protocol was set to HTTPSThe ALB talks HTTPS to the target and the handshake failsFix
- 1
What does the error look like?
HTTP 502: Bad gatewayHTTPCode_ELB_502_Count
Cause 1 of 4
The target closes the connection sooner than the ALB idle timeout
1Check
The AWS docs list a target closing the connection with a TCP RST or FIN while the load balancer has an outstanding request, and tell you to check that the keep-alive duration of the target is shorter than the idle timeout of the load balancer. Node.js closes idle connections quickly unless you change it.
aws elbv2 describe-load-balancer-attributes --load-balancer-arn "$ALB_ARN" \
--query "Attributes[?Key=='idle_timeout.timeout_seconds']"2Fix
Node.js closes idle connections after 5 seconds by default. Set keepAliveTimeout longer than the idle timeout value you read above.
const server = app.listen(3000);
// longer than the ALB idle timeout from the check above
server.keepAliveTimeout = 65 * 1000;3Verify
Run steady traffic for a few minutes and watch the 502 count stay at zero.
aws cloudwatch get-metric-statistics --namespace AWS/ApplicationELB --metric-name HTTPCode_ELB_502_Count --dimensions Name=LoadBalancer,Value=app/my-alb/abc123 --start-time 2026-11-17T00:00:00Z --end-time 2026-11-17T01:00:00Z --period 300 --statistics SumConfirmed by docs.aws.amazon.com
Cause 2 of 4
Traffic from the ALB to the target port is blocked or refused
1Check
The docs name a TCP RST on connect, and an unreachable host. They say to check whether traffic is allowed from the load balancer subnets to the targets on the target port. Also check that the app listens on the port the target group uses.
sudo ss -ltnp | grep node2Fix
Allow the target port in the target's security group from the load balancer's security group, and make Node.js listen on the target group port on an address the ALB can reach.
// listen on all interfaces, not only 127.0.0.1
app.listen(3000, '0.0.0.0');3Verify
The target shows healthy in the target group.
aws elbv2 describe-target-health --target-group-arn "$TG_ARN"Confirmed by docs.aws.amazon.com
Cause 3 of 4
The response is malformed or the header block is over 32 K
1Check
The docs list two causes: a malformed response or invalid headers, and a response header over 32 K for the whole header.
curl -s -D - -o /dev/null http://127.0.0.1:3000/login | wc -c2Fix
Trim the cookies and headers the route sets, and fix anything that writes an invalid header.
// keep cookies small: store an id, not the whole profile
res.cookie('sid', sessionId, { httpOnly: true, secure: true });3Verify
The check prints a number well under 32768 and the route returns 200 through the ALB.
curl -i https://example.com/loginConfirmed by docs.aws.amazon.com
Cause 4 of 4
The ALB talks HTTPS to the target and the handshake fails
1Check
The docs list an SSL handshake error when the load balancer connects to a target. The target must present a certificate and key and support a cipher and protocol that the ALB offers.
openssl s_client -connect 10.0.1.25:3000 </dev/null 2>&1 | head -n 202Fix
Serve HTTPS on the target with a certificate and key in the format the ALB security policy allows, on a port the target group uses. If you do not need encryption to the target, create a target group with the HTTP protocol instead and move the listener to it.
import https from 'node:https';
import fs from 'node:fs';
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt'),
}, app).listen(3000);3Verify
Requests through the ALB return 200.
curl -i https://example.com/healthConfirmed by docs.aws.amazon.com
How do I stop it coming back?
- Set the Node.js keep-alive timeout above the ALB idle timeout in every service behind an ALB.
- Alarm on HTTPCode_ELB_502_Count so a spike is seen before users report it.
- Keep cookies small, and log response header size on routes that set many.
- Test a target group change with the health check before shifting traffic.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Dispatch ProA real-time logistics platform: Flutter apps, Spring Boot services and a Kafka event pipeline on AWS.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Servers
nginx 502 Bad Gateway in front of a Node.js app
connect() failed (111: Connection refused) while connecting to upstream
A 502 means nginx reached for your Node.js app and got nothing usable back.
5 causes, each with a fixBack end
API Gateway gives up on a slow Lambda or Node.js backend
$context.integrationErrorMessage in the access log shows the integration error
API Gateway stops waiting for the backend at its integration timeout: 29 seconds by default on REST APIs, a fixed 30 seconds on HTTP APIs.
4 causes, each with a fixBack end
cdk synth says --app is required
--app is required either in command-line, in cdk.json or in ~/.cdk.json
The CDK CLI needs a command that runs your app and finds it in three places: the --app option, cdk.json in the project folder, or cdk.json in your home folder.
3 causes, each with a fixBack end
The AWS SDK in Node.js cannot find any credentials
Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
The AWS SDK walks a fixed credential chain: code, environment variables, the shared files in ~/.aws, then role sources such as ECS or EC2.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix