Deploy ReplicaSet With Keyfile Authentication

① Create a keyfile

openssl rand -base64 756 > mongodb.key
# chmod 400 <path-to-keyfile>

② Copy the keyfile to each replica set member

sudo mv mongodb.key /var/lib/mongodb
sudo chown mongodb:mongodb /var/lib/mongodb/mongodb.key
sudo chmod 400  /var/lib/mongodb/mongodb.key

③ Start each member of the replica set with access control enabled

net:
  port: 27017
  bindIp: 127.0.0.1,<hostname(s)|ip address(es)>
security:
  keyFile: /var/lib/mongodb/mongodb.key
  authorization: enabled
replication:
  replSetName: <replicaSetName>
sudo systemctl start mongod.service

④ Connect to a member of the replica set over the localhost interface.

The localhost interface is only available since no users have been created for the deployment. The localhost interface closes after the creation of the first user.

⑤ Initiate the replica set.

rs.initiate(
  {
    _id : "myReplSet",
    members: [
      { _id : 0, host : "mongo1.example.net:27017" },
      { _id : 1, host : "mongo2.example.net:27017" },
      { _id : 2, host : "mongo3.example.net:27017" }
    ]
  }
)

⑥ Create the user administrator.

admin = db.getSiblingDB("admin")
admin.createUser(
  {
    user: "fred",  // or name useradmin
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

⑦ Authenticate as the user administrator.

Authenticate to the admin database.

In mongosh, use db.auth() to authenticate. For example, the following authenticate as the user administrator fred:

db.getSiblingDB("admin").auth("fred", passwordPrompt()) // or cleartext password

Alternatively, connect a new mongosh instance to the primary replica set member using the -u username, -p password, and the --authenticationDatabase parameters.

mongosh -u "fred" -p  --authenticationDatabase "admin"


Create root user

admin = db.getSiblingDB("admin")
admin.createUser(
  {
    user: "root",
    pwd: "xxx",
    roles: [ { role: "root", db: "admin" } ]
  }
)
最后修改日期: 18 7 月, 2025

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。