Saturday, February 2, 2019

amazon web services - Hide EC2 Instance Behind Load Balancer



In AWS, I have an EC2 instance which currently allows incoming traffic on port 80. I am hosting an API on this instance and so currently I can hit the API endpoints using Postman at the public IP of the EC2 instance. So far so good.



Next, I have set up an internet-facing, application load balancer with an SSL cert and a subdomain (call it api.whatever.com). The security group for the load balancer prevents port 80 traffic, but allows port 443 (HTTPS) traffic. And the load balancer is configured to forward requests to the EC2 instance via port 80.




So, I can hit my API and get a response through the load balancer, for example like https://api.whatever.com/something.php. While http://api.whatever.com/something.php is unreachable because port 80 is blocked. This is what I want.



However, now what I want to do is prevent the EC2 instance from responding to HTTP requests from anywhere other than the load balancer. But of course if I remove port 80 from the EC2 security group, the load balancer can no longer contact it because it uses port 80. I was looking for an IP address of the load balancer so I could whitelist that IP in the security group on port 80, but I was unable to find such a thing.



How can I exclude port 80 access to my EC2 instance to everything except the load balancer?


Answer



Remove global access to port 80 for the instance, and only permit traffic from the ELB's security group.



This can be done via the console:




enter image description here



or via the CLI:



aws ec2 authorize-security-group-ingress
--group-name MyEC2Group
--protocol tcp
--port 80
--source-group MyELBGroup


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...