简体   繁体   中英

Getting error: “localhost:27017: [Errno 111] Connection refused” while connecting to mongoDB on Heroku but works fine on my computer

I'm using PyMongo. Everything works fine and can connect fine to MongoDB, that's on my computer but when I put the scripts on GitHub and run them through Heroku for my Discord bot I keep on getting the error saying:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

I don't know why this happens while it works fine on my computer, I put pymongo in requirements.txt . Below is how I connect to MongoDB (with PyMongo):

import pymongo
from pymongo import MongoClient, ReturnDocument
dbclient = MongoClient('mongodb://localhost:27017/')
# On Heroku I get error:"localhost:27017: [Errno 111] Connection refused"

On your local machine, you can set the specific port to use (eg 27017). Does heroku choose the port for you instead?

Heroku isn't a host where you can run arbitrary things on the local machine. You'll have to connect to a non-local MongoDB host instead of localhost . One easy way to do that is to select an appropriate add-on and add it to your app.

For example, you might choose to use the free starter version of mLab MongoDB . You can provision this add-on by running

heroku addons:create mongolab:sandbox

This addon will set an environment variable MONGODB_URI for you , which you can use to connect:

import os

# Use the default argument if you don't want to have to set MONGODB_URI on your
# dev machine
mongodb_uri = os.getenv('MONGODB_URI', default='mongodb://localhost:27017/')

dbclient = MongoClient(mongodb_uri)

I decided to not use local host because i couldn't understand it, I'm now using an URL given by mongo DB to with my username and password which you can create by going to https://www.mongodb.com/cloud and creating a project and a cluster and collections then the url should be given to you, url should be something like this mongodb+srv://<username>:<password>@cluster-apc2i.mongodb.net/test?retryWrites=true&w=majority add that url to your script like this

client = MongoClient("mongodb+srv://<username>:<password>@cluster-apc2i.mongodb.net/test?retryWrites=true&w=majority")

Also make sure to add 0.0.0.0/0 to your allowed ip, that ip means all ip addresses with details are allowed to access, if you don't add that you may get an error saying, time out and other URL may be given to you after you create a new user from the Database Access Pannel on the left

You should delete the mongod.lock lock from /var/lib/mongodb After that you can restart the service.

Also you can try to change part of client code by

client = MongoClient('localhost', 27017)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM