Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB replica set on single machine

Tags:

mongodb

I have a single instance (I.e. no virtualisation) of Linux running on a server. I have a single mongod instance that is running. Moving to production I want to implement replica sets. Everything I've read talks about running mongod on multiple machines.

I understand it might not be best practice however is it possible to run replica sets of the same machine. Also, the machine has two hard drives. I want the primary DB to be on the first HD and the replica set on the second hard drive.

Is this setup possible?

like image 784
johhny B Avatar asked Oct 18 '22 16:10

johhny B


1 Answers

Here's how I did it on Ubuntu. I wanted to use systemd for the second instance.

Copy our existing MongoDB conf:

sudo cp /etc/mongod.conf /etc/mongod_repl.conf

sudo pico /etc/mongod_repl.conf

Change these lines:

storage:
  dbPath: /var/lib/mongodb_repl

systemLog:
  path: /var/log/mongodb/mongod_repl.log

net:
  port: 27018

replication:
  replSetName: rs0

Create the dirs and files, and assign permissions

sudo mkdir /var/lib/mongodb_repl
sudo chown mongodb:mongodb /var/lib/mongodb_repl
sudo touch /var/log/mongodb/mongod_repl.log
sudo chown mongodb:mongodb /var/log/mongodb/mongod_repl.log

Copy our existing startup file:

sudo cp /lib/systemd/system/mongod.service /etc/systemd/system/mongod_repl.service

If you can't find mongod.service, sudo systemctl status mongod. It looks like:

Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)

sudo pico /etc/systemd/system/mongod_repl.service

Change these lines:

ExecStart=/usr/bin/mongod --config /etc/mongod_repl.conf
PIDFile=/var/run/mongodb/mongod_repl.pid

Let systemctl know we've made some changes: sudo systemctl daemon-reload

Try start it our second server:

sudo systemctl start mongod_repl
sudo systemctl status mongod_repl

If it's not running, have a look at the logs:

sudo tail -n100 /var/log/mongodb/mongod_repl.log
sudo journalctl -n100 -u mongod_repl

(You can add a -f to either of those lines to tail the log)

Log in mongo --port 27018

Great! Now you have a second MongoDB server up and running.

Configure your original server to use the same replication set: sudo pico /etc/mongod.conf

Add this:

replication:
   replSetName: rs0

Restart MongoDB sudo systemctl restart mongod

Now you should be able to go through the process of rs.initiate() on your primary, and then add 127.0.0.1:27018 as your secondary.

like image 193
Jason Norwood-Young Avatar answered Oct 21 '22 05:10

Jason Norwood-Young