EC2 WebSocket – Cannot Get WebSocket Connection Working with EC2 and Application Load Balancer

amazon ec2amazon-albamazon-elbamazon-web-serviceswebsocket

I have an aws application load balancer with an https listener on port 9999, forwarding to a group on port 9999 with an ec2-instance being the target.

If I run my websocket server with the host name configured to my domain api.example.com, then when the client tries to open a websocket connection it gets:

Error during WebSocket handshake: Unexpected response code: 502

However, if I configure my websocket server with an empty string instead of the domain, then it connects just fine!

This is problematic because the server I am intending to run on this instance automatically launches a websocket server ONLY IF there is a websocket host name configuration provided, so a blank string means the websocket server will never launch! I would prefer to not have to hack the library to get around that condition. So I am wondering, why in the world a blank string works, but the domain name does not?

I tried localhost, the ip of the box, etc, everything results in a 502 except a blank string!

Best Answer

The ALB does not use a host name for the health check. Thus, if your server does not support requests without host names, the health check will fail, resulting in 5xx errors when accessing the ALB.

  • Check the target group the ALB is using for health check errors
  • Check your application server logs for health check related errors

If your server does not support this you have two options:

  • Use a proxy (e.g. nginx) on your server that can handle requests without host name, and handle the problem there
  • Override the ALB health check port, redirecting it to something that returns HTTP 200 all the time (e.g. an Apache running on the same host, but on another port).
Related Topic