Skip to content

Instantly share code, notes, and snippets.

@marsyang1
Last active November 2, 2021 02:44
Show Gist options
  • Save marsyang1/f4bbe2109c38e2b4b54366b008bb0a80 to your computer and use it in GitHub Desktop.
Save marsyang1/f4bbe2109c38e2b4b54366b008bb0a80 to your computer and use it in GitHub Desktop.
Build MongoDB replicaSet by using docker

Script for all server

cd PATH_TO_STORE_DATA
mkdir conf
mkdir db
mkdir backup
mkdir tmp
touch conf/mongod.conf
touch conf/replicaSet.js
date +%s | sha256sum | base64 | head -c 32 > conf/keyfile
chmod 400 conf/keyfile

docker run -d -p 27017:27017 \
--restart always \
-e TZ=THE_TIMEZONE_YOU_WANT \
-v /PATH_TO_STORE_DATA/mongodb:/data/mongo:z \
--user "$(id -u):$(id -g)" \
--name mongo \
-e MONGO_INITDB_ROOT_USERNAME=MONGO_ADMIN_NAME \
-e MONGO_INITDB_ROOT_PASSWORD=MONGO_ADMIN_PASSWORD \
mongo:5.0.3-focal  --config /data/mongo/conf/mongod.conf

Suggest use the mongosh to setup replicaSet , https://docs.mongodb.com/mongodb-shell/

mongosh mongodb://SERVER_1_PUBLIC_IP:27017 -u MONGO_ADMIN_NAME -p MONGO_ADMIN_PASSWORD replicaSet.js
# mongod.conf
# reference to https://github.com/bitnami/bitnami-docker-mongodb
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /data/mongo/db
journal:
enabled: true
directoryPerDB: false
# engine:
# wiredTiger:
# where to write logging data.
# combine log by console with docker logs
systemLog:
verbosity: 0
quiet: false
#destination: file
#logAppend: true
#logRotate: reopen
#path: /data/mongo/logs/mongodb.log
# network interfaces
net:
port: 27017
unixDomainSocket:
pathPrefix: /tmp/mongo
ipv6: false
bindIpAll: true
# how the process runs
# suggest not to enable it
# https://stackoverflow.com/questions/63210765/is-processmanagement-fork-to-true-needed-when-mongodb-is-only-application-runn
# processManagement:
# security options
security:
authorization: enabled
keyFile: /data/mongo/conf/keyfile
#operationProfiling:
## If you dont need the replication , just comment on it
replication:
replSetName: rs0
#sharding:
# set parameter options
setParameter:
enableLocalhostAuthBypass: false
## Enterprise-Only Options:
#auditLog:
#snmp:
# for setup replicaSet
rsconf = {
_id : "rs0",
members: [
{ _id : 0, host : "SERVER_1_PUBLIC_IP:27017", priority:1 },
{ _id : 0, host : "SERVER_2_PUBLIC_IP:27017", priority:1 },
{ _id : 0, host : "SERVER_3_PUBLIC_IP:27017", priority:1 }
]
}
rs.initiate(rsconf);
rs.conf();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment