On one server create a key file. Copy this key file to all other servers that will participate in the replica set
mkdir -p /opt/mongodb/keys/ openssl rand -base64 756 > /opt/mongodb/keys/$(date '+%Y-%m-%d').key chmod 400 /opt/mongodb/keys/$(date '+%Y-%m-%d').key chown -R mongodb:mongodb /opt/mongodb/keys/$(date '+%Y-%m-%d').key
On each server, edit /etc/mongo.conf and add the keyfile to the security section and define a replica set
security: authorization: enabled keyFile: /etc/mongodb/keys/mongo-key #replication: replication: replSetName: "myReplicaSet"
Restart MongoDB on each node.
On one server, use mongosh to enter the MongDB shell.
rs.initiate( { _id: "myReplicaSet", members: [ { _id: 0, host: "mongohost1.example.net" }, { _id: 1, host: "mongohost2.example.net" }, { _id: 2, host: "mongohost3.example.net" } ] })
Use rs.status() to view the status of the replica set. If it is stuck in STARTING … check connectivity. If the port is open, I ran into a snag with some replacement servers. They’ve got temporary hostnames. But you cannot add a host on itself — it ignores that you typed mongohost1.example.net … and it takes it’s hostname
value. And then sends that value to the other servers in the replica set. If you cannot change the hostname to match what you want, there is a process to change the hostname in a replicaset.