This article originally published here. In this demonstration, we see why we are getting a timeout error when deploying a lambda functions to a public subnet.
I will deploy a VPC with an Internet gateway to demonstrate this error I am not going to deploy any resources in a private subnet, so for the moment I will not create a NAT gateway. After deploying, my VPC belongs as below.
I will deploy a sample Lambda function with role created by default in the vpc-1 in public subnet and I added necessary lambda layers.
Below is the code:
import requests
def lambda_handler(event, context):
url = 'https://swapi.dev/api/people/4/'
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {
'statusCode': response.status_code,
'body': 'Failed to fetch data from SWAPI'
}
General configuration
VPC configuration:
Although, the public subnet has a route (0.0.0.0/0)towards internet gateway, the function test will fall into task timed out because the Lambda function itself does not have a publicly accessible IP address.
Test python function
Now I will deploy my function to a private subnet with NAT gateway in the public subnet. In the route table of the private subnet, I will add a route to 0.0.0.0/0 towards my NAT gateway. I will do a test again.
Private subnet route table
Test python after private subnet
This is the best practice for a Lambda function to access the resources through internet. In the next article, we will see how to access AWS services (s3,RDS, DynamoDB)from private subnet without NAT.
Top comments (0)