我的场景:
我有一台linux服务器被加入到阿里云数据库mongodb的白名单了,我想通过这台服务器在我家访问阿里云数据库mongodb
1. 首先将要linux服务器的端口开放出来确定防火墙不阻碍。
2. 准备工作
阿里云 数据库 URL
mongodb://账号:密码@dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com:3717,dds-uf66d90a9c38f2a42679-pub.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-70730161&maxPoolSize=20&minPoolSize=1
服务器ip
your_linux_server_ip
服务器端口号
3717
3.建立 SSH 隧道
3.1 简单连接
ssh -L 3717:mongo.aliyun.com:3717 your_username@your_linux_server_ip
3.2 调试连接
ssh -v -N -L 3717:dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com:3717 your_username@your_linux_server_ip
参数解释:
-L
参数用于进行本地端口转发
-N
参数(只转发,不执行远程命令)
-v
(详细模式)来观察连接过程
确认隧道一直开启
命令执行后,保持终端窗口不要关闭,类似如下日志已经建立隧道了
debug1: Connection to port 3717 forwarding to dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717 requested.
debug1: channel 3: new direct-tcpip [direct-tcpip] (inactive timeout: 0)
debug1: Connection to port 3717 forwarding to dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717 requested.
debug1: channel 4: new direct-tcpip [direct-tcpip] (inactive timeout: 0)
debug1: channel 2: free: direct-tcpip: listening port 3717 for dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717, connect from 127.0.0.1 port 55199 to 127.0.0.1 port 3717, nchannels 5
debug1: channel 4: free: direct-tcpip: listening port 3717 for dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717, connect from 127.0.0.1 port 55201 to 127.0.0.1 port 3717, nchannels 4
debug1: channel 3: free: direct-tcpip: listening port 3717 for dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717, connect from 127.0.0.1 port 55200 to 127.0.0.1 port 3717, nchannels 3
debug1: Connection to port 3717 forwarding to dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717 requested.
debug1: channel 2: new direct-tcpip [direct-tcpip] (inactive timeout: 0)
debug1: channel 2: free: direct-tcpip: listening port 3717 for dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com port 3717, connect from 127.0.0.1 port 55207 to 127.0.0.1 port 3717, nchannels 3
4.最后用mongodb客户端连接
4.1 使用单节点直连,不指定 replicaSet
不加 replicaSet=xxx
,等于是告诉客户端 “我就连这个节点”,不会尝试获取副本集成员信息
注意是localhost,不是其他ip,是本地转发。
mongodb://用户:密码@localhost:3717/admin
注:副本集配置问题
如果你连接的是副本集,在 URI 中使用了 replicaSet=mgset-70730161
。客户端会在建立连接后尝试访问副本集中的所有成员。
但此时你只通过隧道连接了一个节点(比如 dds-uf66d90a9c38f2a41756-pub
),其余副本成员不可访问,会导致客户端连接失败。
例如这种连接会有问题
mongodb://用户:密码@localhost:3717/admin?replicaSet=mgset-70730161&maxPoolSize=20&minPoolSize=1
4.2 多节点直连
所有副本节点的 3717 端口都转发出来
ssh \
-v -N -L 3717:dds-uf66d90a9c38f2a41756-pub.mongodb.rds.aliyuncs.com:3717 \
-v -N -L 3718:dds-uf66d90a9c38f2a42679-pub.mongodb.rds.aliyuncs.com:3717 \
root@your_linux_server_ip
然后修改 URI,把主机地址替换成 localhost:3717
和 localhost:3718
:
mongodb://用户:密码@localhost:3717,localhost:3718/admin?replicaSet=mgset-70730161
目前测试这种连接最稳
mongodb://用户:%密码@localhost:3717/admin