mongodb replica set 实战

mongodb replica set 实战

卸载MongoDB

  • sudo systemctl stop mongodd
  • sudo yum erase $(rpm -qa | grep mongodb-org)
  • sudo rm -r /var/log/mongodb
  • sudo rm -r /var/lib/mongo
  • sudo rm -r /var/run/mongodb

安装MongoDB

  • 创建 ,/etc/yum.repos.d/mongodb-org-3.4.repo
1
2
3
4
5
6
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
  • 安装,sudo yum install -y mongodb-org
  • 启动,systemctl start mongod
  • 开机启动,systemctl enable mongod
  • 测试外网能力,mongo --host xxxx --port 27017
  • 修改,/etc/mongod.conf的bindIp, bindIp: 0.0.0.0
  • 重启mongo,systemctl restart mongod

开启replica set身份验证(Keyfiles)

  • 生成keyfile,
    openssl rand -base64 756 > path-to-keyfile
    chmod 400 path-to-keyfile
  • 拷贝keyfile到每台服务器相同位置
  • 配置每台mongo服务器的keyfile,修改/etc/mongod.conf,删除security前的#,增加配置项,keyFile: /etc/mongo/yxkeyfile
  • 开启replication, 修改/etc/mongod.conf,删除replication前的#,增加配置项,replSetName: test
  • 重启mongo,systemctl restart mongod
  • 选择一台主机作为primary,执行
    rs.initiate( {
    _id : "yxrep",
    members: [ { _id : 0, host : "10.10.10.161:27017" } ]
    })
  • 添加secondary,rs.add("10.10.10.162:27017")
  • 执行mongo命令
  • 创建管理员:
    admin = db.getSiblingDB("admin")
    admin.createUser(
    {
    user: "admin",
    pwd: "admin$magic",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
    }
    )
  • 管理员登录:
    db.getSiblingDB("admin").auth("admin", "admin$123" )

    或者
    
    `mongo -u "admin" -p "admin$123" --authenticationDatabase "admin"`
    
  • 创建DB读写用户
    use dashboard
    db.createUser(
    {
    user: "test",
    pwd: "test$123",
    roles: [ { role: "readWrite", db: "dashboard" },
    { role: "read", db: "dashboard" } ]
    }
    )

  • 用户登录
    mongo --port 27017 -u "test" -p --authenticationDatabase "dashboard"