My local MongoDB is refusing to connect with AWS SAM Lambda in python

0

I have set up an AWS Lambda function using the AWS SAM app. I have also downloaded local MongoDB on my machine. I am trying to make a connection between AWS Lambda and MongoDB. You can see my code below:

import json
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['Employee']

def lambda_handler(event, context):
    information = mydb.employeeInformation
    record = {
        'FirstName' : 'Rehan',
        'LastName' : 'CH',
        'Department' : "IT" 
    }
    information.insert_one(record)
    print("Record added")

    return {
        "statusCode": 200,
        "body": json.dumps(
            {
                "message": "hello world",
                # "location": ip.text.replace("\n", "")
             }
    ),
}

When I run the sam app using command

sam local invoke

it throws an error that you can see below:

[ERROR] ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 62b16aa14a95a3e56eb0e7cb, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localho    raise ServerSelectionTimeoutError(, line 227, in _select_servers_looprtn_support

I also have searched for this error and eventually, I found some but didn't get help from them. That's why I have to post it again.

Its my first time interaction with MongoDB. Can someone tell me how do I resolve this error, or where I am doing wrong?

2 Answers
1

SAM local invoke runs in a Docker container so you'll need to configure it so the Lambda in the Docker container can connect to localhost of the machine.

The way you configure this will depend on what OS you are running, you can refer to this closed issue for aws-sam-cli for more information. Here is also the Docker documentation if you are using Docker-for-mac or Docker-for-Windows or Docker-for-Linux.

AWS
answered 2 years ago
0

I have resolved my issue. Whenever we are trying to connect our locally created SAM app with local MongoDB then we should set up our MongoDB on Docker. Then set the IP address of the container to the connection string.

Initially, I was trying this with localhost:

client = pymongo.MongoClient('mongodb://localhost:27017/')

What to change? We only have to use the IP address of the dockerized MonogoDB, and it will look like this:

client = pymongo.MongoClient('mongodb://172.17.0.2:27017/')
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions