Unveiling the Mystery: Decoding the Dilemma of Lambda Deployment in Private Subnets

AWS server-less experiments : Why can’t you deploy a lambda function in a public subnet?

In this demonstration, we will 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 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. I added necessary lambda layer for import requests. 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:

Test:

Route table of private subnet after NAT deployment in public subnet

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.

It works! It looks simple, but sometimes we lose more time scratching our head to understand why doesn't it works.

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.

If you have any concerns/doubts/help follow me regarding this post, you can DM on LinkedIn, and also I invite you to my discord server and stay updated on cloud and DevOps.

Did you find this article valuable?

Support Ashok kumar B by becoming a sponsor. Any amount is appreciated!