如何解决公网无法访问阿里云ECS搭建的MongoDB服务

2,146 阅读1分钟

最近为了学习后端购买了一台阿里云ECS云服务器(专用网络) 环境如下: OS:Ubuntu16.04, MongoDB:v4.0.1

尝试着安装了MongoDB并进行了相应的配置,搜索了一些资料发现关键在于三点:

  1. MongoDB的bindIp配置: MongoDB默认的配置文件中,bindIp选项默认是localhost,也就是说默认只有安装了MongoDB的主机自己能够访问。所以如果需要外网的主机能够访问MongoDB服务,首先需要更改bindIp选项,将其设置为指定的IP地址(x.x.x.x, ...)者绑定所有的IP地址(0.0.0.0 )。MongoDB 3.6之后的版本新增了bindIpAll选项,true代表绑定所有IP地址。 配置文件如下:
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIpAll: true
  
# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
  1. Linux防火墙iptables的配置: 在bash中输入sudo iptables -A INPUT -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT sudo iptables -A OUTPUT -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT 开放MongoDB的端口。 接着输入iptables-saveiptables-restore保存iptables的配置信息以免主机重启后需要重新配置。

  2. ECS主机的安全组规则配置:

经过以上的配置后,就能够远程连接阿里云ECS上搭建的MongoDB服务了。