问题描述
我已按照教程此处创建具有公共和私有子网的VPC.
I've followed the tutorial here to create a VPC with public and private subnets.
然后,我在公共子网中设置了一个AWS lambda函数,以测试它是否可以连接到外部互联网.
Then I set up an AWS lambda function inside the public subnet to test if it could connect to the outside internet.
这是我用python3编写的lambda函数
Here's my lambda function written in python3
import requests
def lambda_handler(event, context):
r = requests.get('http://www.google.com')
print(r)
当我在VPC的公共子网内设置http://www.google.com
的内容时,上述函数无法获取http://www.google.com
的内容.
The function above failed to fetch the content of http://www.google.com
when I set it inside the public subnet in a VPC.
这是错误消息:
我不明白为什么.
公共子网的路由表如下:
The route table of the public subnet looks like this:
对http://www.google.com
的GET
请求应与igw-XXXXXXXXX
目标匹配.为什么Internet网关(igw)无法将请求传递到http://www.google.com
并取回网站内容?
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?
该文章说,我必须设置私有子网中的lambda函数以便可以访问Internet.
This article says that I must set the lambda function inside the private subnet in order to have internet access.
但这并不能解释为什么我不能在公共子网中设置lambda函数.
But it doesn't explain why I can't set the lambda function inside the public subnet.
推荐答案
即使Lambda函数在VPC的公共子网中运行,您的Lambda函数也无法访问Internet的原因是Lambda函数没有,并且不能拥有公共IP地址.除非您具有公共IP,否则您无法通过VPC的Internet网关将流量发送到Internet.您将需要通过NAT进行路由.
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 to the internet, via the VPC's Internet Gateway, unless you have a public IP. You would need to route through a NAT.
VPC公共子网中流量的默认路由目标是 Internet网关(IGW),并且由于Lambda功能只有一个专用IP,因此从Lambda功能发送到互联网的所有数据包都将在IGW处丢弃.
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.
如果您的Lambda函数实际上不需要访问VPC内部的私有资源,则通常不需要将Lambda部署到VPC中.但是,如果确实需要,则可以在专用子网中运行Lambda函数,并确保从该子网到公用子网中的NAT实例或NAT网关的默认路由.并配置一个IGW.注意:如果Lambda仅需要访问VPC中的资源(例如,私有子网中的RDS数据库)和/或访问全部通过私有 VPC端点,那么您根本不需要通过NAT路由.
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. Note: if the Lambda only needs access to resources in the VPC (e.g. an RDS database in a private subnet) and/or to AWS services that are all available via private VPC Endpoint then you don't need to route through NAT at all.
这篇关于为什么VPC的公共子网内的AWS Lambda函数无法连接到互联网?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!