在 CentOS 上连接 MongoDB,通常分为 本地连接 和 远程连接 两种情况。下面从安装、配置到连接一步步说明(以 CentOS 7/8 为例,MongoDB 6.x 为例)。
cat > /etc/yum.repos.d/mongodb-org-6.0.repo <<EOF
[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
EOF
yum install -y mongodb-org
systemctl start mongod
systemctl enable mongod
systemctl status mongod
mongo
mongosh
连接成功后你会看到:
test>
vim /etc/mongod.conf
重点修改:
bindIp: 0.0.0.0
默认是:
bindIp: 127.0.0.1
⚠️ 生产环境建议只开放指定 IP,而不是
0.0.0.0
systemctl restart mongod
firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
iptables -A INPUT -p tcp --dport 27017 -j ACCEPT
use admin
db.createUser({
user: "admin",
pwd: "Admin@123",
roles: [{ role: "root", db: "admin" }]
})
vim /etc/mongod.conf
添加或修改:
security:
authorization: enabled
重启:
systemctl restart mongod
mongosh -u admin -p Admin@123 --authenticationDatabase admin
mongosh "mongodb://admin:Admin@123@<服务器IP>:27017/admin"
常见工具:
连接字符串示例:
mongodb://admin:Admin@123@192.168.1.100:27017/admin
Connection refused
✅ 检查:
Authentication failed
✅ 检查:
| 场景 | 命令 |
|---|---|
| 本地连接 | mongosh |
| 远程连接 | mongosh "mongodb://IP:27017" |
| 带账号连接 | mongosh -u user -p password --authenticationDatabase admin |
如果你愿意,可以告诉我:
我可以按你的环境给你精确命令。