Skip to content

Instantly share code, notes, and snippets.

@ssprasad100
Forked from leetreveil/start-mongo-replset.sh
Created November 5, 2019 06:37
Show Gist options
  • Save ssprasad100/9f1fc1c19b972d1a6098387ed7429d60 to your computer and use it in GitHub Desktop.
Save ssprasad100/9f1fc1c19b972d1a6098387ed7429d60 to your computer and use it in GitHub Desktop.
Shell scripts to create a mongodb replica set and sharded cluster locally
#!/bin/bash
# shell script to create a simple mongodb replica set (tested on osx)
set -e
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
default=$(tput sgr0)
function finish {
pids=(`cat ~/mongosvr/rs-*.pid`)
for pid in "${pids[@]}"
do
kill $pid
wait $pid
done
}
trap finish EXIT
mkdir -p ~/mongosvr/rs-0
mkdir -p ~/mongosvr/rs-1
mkdir -p ~/mongosvr/rs-2
mongod --shardsvr --dbpath ~/mongosvr/rs-0 --replSet set --rest --port 27091 \
--config . --pidfilepath ~/mongosvr/rs-0.pid 2>&1 | sed "s/.*/$red&$default/" &
mongod --shardsvr --dbpath ~/mongosvr/rs-1 --replSet set --rest --port 27092 \
--config . --pidfilepath ~/mongosvr/rs-1.pid 2>&1 | sed "s/.*/$green&$default/" &
mongod --shardsvr --dbpath ~/mongosvr/rs-2 --replSet set --rest --port 27093 \
--config . --pidfilepath ~/mongosvr/rs-2.pid 2>&1 | sed "s/.*/$yellow&$default/" &
# wait a bit for the first server to come up
sleep 5
# call rs.initiate({...})
cfg="{
_id: 'set',
members: [
{_id: 1, host: 'localhost:27091'},
{_id: 2, host: 'localhost:27092'},
{_id: 3, host: 'localhost:27093'}
]
}"
mongo localhost:27091 --eval "JSON.stringify(db.adminCommand({'replSetInitiate' : $cfg}))"
# sleep forever
cat
#!/bin/bash
# shell script to create a simple mongodb sharded cluster locally.
# Requires a replica set to be already running, you can run
# start-mongo-replset.sh first to start a replica set.
set -e
red=$(tput setaf 1)
green=$(tput setaf 2)
default=$(tput sgr0)
function finish {
pid=`cat ~/mongosvr/shard-config-0.pid`
kill $pid
wait $pid
}
trap finish EXIT
mkdir -p ~/mongosvr/config-0
# start up the mongodb config server for the shards
mongod --configsvr --dbpath ~/mongosvr/config-0 --port 27019 \
--config . --pidfilepath ~/mongosvr/shard-config-0.pid 2>&1 | sed "s/.*/$red&$default/" &
sleep 3
mongos --configdb localhost:27019 | sed "s/.*/$green&$default/" &
sleep 3
# add the first replica set instance as a shard, the others will be discovered automatically by mongos
mongo --eval "JSON.stringify(sh._adminCommand( { addShard : 'set/localhost:27091' } , true ))"
# enable sharding on the test database
mongo --eval "JSON.stringify(sh._adminCommand( { enableSharding : 'test' } ))"
# sleep forever
cat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment