文章内容

2019/12/30 11:38:20,作 者: 黄兵

MongoDB如何设置远程连接

在Ubuntu中如何设置MongoDB远程连接呢?具体步骤如下:


一、设置您的账户

首先ssh登录服务器,之后进入mongo shell mongo,设置一个用户名:mongo_user,并赋予读写访问权限。

use project_db

db.createUser({
    user: 'mongo_user',
    pwd: 'secretPassword',
    roles: [{ role: 'readWrite', db:'project_db'}]
})


二、启用身份验证,并设置对所有IP的mongodb的访问权限

在Ubuntu上面找到MongoDB的配置文件:

sudo vim /etc/mongod.conf

查找该net行,该行当前将MongoDB连接限制为localhost,将bindIp: 127.0.0.1改成0.0.0.0

向下滚动到该#security:部分,然后添加以下行。确保取消注释该行。security:

security:
  authorization: 'enabled'

修改之后保存。


三、在云服务器上面开启相应端口

如果您的服务器托管在云服务器厂商,需要开放相应的端口,以允许远程连接。


四、重启MongoDB进程

sudo service mongod restart

确保mongo在ssh中仍然可以登录。

# to access the admin database
ubuntu:~$ mongo -u admin -p myadminpassword 127.0.0.1/admin
# to access the other databases
ubuntu:~$ mongo -u user1 -p user1password 127.0.0.1/sampledb



使用pymongo与您的远程服务器的MongoDB连接

import pymongo

client = pymongo.MongoClient("mongodb://mongo_user:secretPassword@123.45.67.89/project_db") # defaults to port 27017
db = client.project_db
# print the number of documents in a collection print db.cool_collection.count()


参考资料:

1、How to connect to your remote MongoDB server

2、Setting up and connecting to a remote MongoDB database


分享到:

发表评论

评论列表

user-ico

yifei on 回复 有用(0

haha


user-ico

zhangsan on 回复 有用(0

请问,云短信中是否已经屏蔽outlook短信

游客0?9y on 2020-01-01 10:11:43

博主恢复:没有。