Why can't an AWS lambda function inside a public subnet in a VPC connect to the internet?

风格不统一 提交于 2019-12-30 04:17:26

问题


I've followed the tutorial here to create a VPC with public and private subnets.

Then I set up an AWS lambda function inside the public subnet to test if it could connect to the outside internet.

Here's my lambda function written in python3

import requests

def lambda_handler(event, context):
    r = requests.get('http://www.google.com')
    print(r)

The function above failed to fetch the content of http://www.google.com when I set it inside the public subnet in a VPC.

Here's the error message:

"errorMessage": "HTTPConnectionPool(host='www.google.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',))", "errorType": "ConnectionError",

I don't understand why.

The route table of the public subnet looks like this:

The GET request to http://www.google.com should match igw-XXXXXXXXX target. Why can't the internet-gateway(igw) deliver the request to http://www.google.com and get back the website content?

This article says that I must set the lambda function inside the private subnet in order to have internet access.

If your Lambda function needs to access private VPC resources (for example, an Amazon RDS DB instance or Amazon EC2 instance), you must associate the function with a VPC. If your function also requires internet access (for example, to reach a public AWS service endpoint), your function must use a NAT gateway or instance.

But it doesn't explain why I can't set the lambda function inside the public subnet.


回答1:


The reason that your Lambda function cannot access the internet, even though the Lambda function is running inside a public subnet of a VPC, is that Lambda functions do not, and cannot, have public IP addresses. You cannot send traffic directly to the internet without a public IP. You would need to route through a NAT.

The default route target for traffic in a VPC public subnet is the Internet Gateway (IGW) and, because the Lambda function only has a private IP, all packets to the internet from the Lambda function will be dropped at the IGW.

If your Lambda function doesn't actually need to reach private resources inside your VPC then you typically don't need to deploy the Lambda into a VPC. But if it does need to, then run the Lambda function in a private subnet and ensure a default route from that subnet to a NAT instance or NAT Gateway in a public subnet. And configure an IGW.



来源:https://stackoverflow.com/questions/52992085/why-cant-an-aws-lambda-function-inside-a-public-subnet-in-a-vpc-connect-to-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!