mongodb单节点改副本集模式

前一阵将三节点的副本集改成了单节点,但后面业务代码出现问题:无法使用事务,因为事务只有在副本集上能用,单节点无法使用,故需要改回副本集模式,而我目前仅有一台服务器,所以考虑在一台服务器上通过容器部署三节点副本集

yml 复制代码
version: "3.8"
services:
  mongo1:
    image: mongo:5.0.31
    container_name: mongo1
    ports:
      - 27017:27017
    volumes:
      - mongo2:/data/db  # 复用你原来的数据
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

  mongo2:
    image: mongo:5.0.31
    container_name: mongo2
    ports:
      - 27018:27017
    volumes:
      - mongo2_data2:/data/db
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

  mongo3:
    image: mongo:5.0.31
    container_name: mongo3
    ports:
      - 27019:27017
    volumes:
      - mongo2_data3:/data/db
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

volumes:
  mongo2:         # 原来的数据卷
  mongo2_data2:
  mongo2_data3:

这里需要注意,docker volume mongo2是保存有数据的volume,所以你需要把它指定为主节点

复制代码
>>> docker exec -it mongo1 mongosh
cfg = {
  _id: "rs0",
  members: [
    { _id: 0, host: "10.6.212.87:27017", priority: 2 },
    { _id: 1, host: "10.6.212.87:27018", priority: 1 },
    { _id: 2, host: "10.6.212.87:27019", priority: 0 }
  ]
}
rs.reconfig(cfg, { force: true })

还有就是启动mongo时,如果加上"--auth"参数,会报如下错误

b 复制代码
Attaching to mongo1, mongo2, mongo3
mongo2  | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo2  | try 'mongod --help' for more information
mongo1  | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo1  | try 'mongod --help' for more information
mongo3  | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo3  | try 'mongod --help' for more information
mongo2 exited with code 2
mongo1 exited with code 2
mongo3 exited with code 2

解决起来有一些麻烦,所以我就干脆把--auth参数去掉了,但会存在安全风险。

还要注意,mongodb比较吃内存,所以在单服务器上要注意内存,不然会被docker停掉。