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개 답변
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
답변함 2년 전
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/')
답변함 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인