title: Why can't an AWS lambda function inside a public subnet in a VPC connect to the internet?
body: <p>I've followed the tutorial <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html" rel="noreferrer">here</a> to create a VPC with public and private subnets.</p>
  
  <p>Then I set up an AWS lambda function inside the public subnet to test if it could connect to the outside internet.</p>
  
  <p>Here's my lambda function written in python3</p>
  
  <pre><code>import requests
  
  def lambda_handler(event, context):
      r = requests.get('http://www.google.com')
      print(r)
  </code></pre>
  
  <p>The function above failed to fetch the content of <code>http://www.google.com</code> when I set it inside the public subnet in a VPC.</p>
  
  <p>Here's the error message:</p>
  
  <blockquote>
    <p>"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",</p>
  </blockquote>
  
  <p>I don't understand why.</p>
  
  <p>The route table of the public subnet looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/0AfBe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0AfBe.png" alt="enter image description here"></a></p>
  
  <p>The <code>GET</code> request to <code>http://www.google.com</code> should match <code>igw-XXXXXXXXX</code> target. Why can't the internet-gateway(igw) deliver the request to <code>http://www.google.com</code> and get back the website content?</p>
  
  <p>This <a href="https://aws.amazon.com/premiumsupport/knowledge-center/internet-access-lambda-function/" rel="noreferrer">article</a> says that I must set the lambda function inside the private subnet in order to have internet access.</p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>But it doesn't explain why I can't set the lambda function inside the public subnet.</p>