Skip to content

Instantly share code, notes, and snippets.

@ianunruh
Last active August 29, 2015 14:04
Show Gist options
  • Save ianunruh/a58fd5955a5ef5565fea to your computer and use it in GitHub Desktop.
Save ianunruh/a58fd5955a5ef5565fea to your computer and use it in GitHub Desktop.
MongoDB sharded cluster on single box
#!/bin/bash
DATA_PATH=/tmp/sharded-cluster
HOSTNAME=$(hostname -f)
killall mongod > /dev/null 2>&1
killall mongos > /dev/null 2>&1
rm -rf $DATA_PATH
mkdir -p $DATA_PATH/rs{0,1}{a,b,c}
mkdir -p $DATA_PATH/cfg{0,1,2}
MONGOD="screen -dm mongod --bind_ip 0.0.0.0"
MONGOS="screen -dm mongos --bind_ip 0.0.0.0"
RS="$MONGOD --smallfiles --oplogSize 128"
echo "Starting config servers"
$MONGOD --configsvr --dbpath $DATA_PATH/cfg0 --port 4000
$MONGOD --configsvr --dbpath $DATA_PATH/cfg1 --port 4001
$MONGOD --configsvr --dbpath $DATA_PATH/cfg2 --port 4002
echo "Starting replica set rs0"
$RS --replSet rs0 --dbpath $DATA_PATH/rs0a --port 5000
$RS --replSet rs0 --dbpath $DATA_PATH/rs0b --port 5001
$RS --replSet rs0 --dbpath $DATA_PATH/rs0c --port 5002
echo "Starting replica set rs1"
$RS --replSet rs1 --dbpath $DATA_PATH/rs1a --port 5010
$RS --replSet rs1 --dbpath $DATA_PATH/rs1b --port 5011
$RS --replSet rs1 --dbpath $DATA_PATH/rs1c --port 5012
echo "Waiting for config servers to become ready"
sleep 10
echo "Starting query router"
$MONGOS --configdb $HOSTNAME:4000,$HOSTNAME:4001,$HOSTNAME:4002 --port 6000
echo "rs.initiate()" | mongo --port 5000
echo "rs.initiate()" | mongo --port 5010
echo "Waiting for replica set leaders to become ready"
sleep 10
cat <<EOQ | mongo --port 5000
rs.add("$HOSTNAME:5001")
rs.add("$HOSTNAME:5002")
EOQ
cat <<EOQ | mongo --port 5010
rs.add("$HOSTNAME:5011")
rs.add("$HOSTNAME:5012")
EOQ
echo "Waiting for replica sets to converge"
sleep 10
cat <<EOQ | mongo --port 6000
sh.addShard("rs0/$HOSTNAME:5000")
sh.addShard("rs1/$HOSTNAME:5010")
sh.status()
EOQ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment