dockerfile:
#base imagesFROM ubuntu:latestMAINTAINER yao.3.li@uconn.edu#install mongodbRUN apt-get updateRUN apt-get -y install curlRUN curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgzRUN tar -zxvf mongodb-linux-x86_64-3.0.6.tgzRUN mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodbRUN export PATH=/usr/local/mongodb/bin:$PATHADD ./run.sh /run.shRUN chmod 777 /run.sh#database directoryRUN mkdir -p /data/dbRUN mkdir -p /data/logRUN touch /data/log/r.logRUN mkdir -p /data/config#portEXPOSE 27017ENTRYPOINT ["/run.sh"]
docker-compose.yml:
version: '3.2'services: primary: image: mongodb ports: - "27017:27017" environment: - role=prime volumes: - ./config/r0.conf:/data/config/c.conf - ./runPrime.sh:/runPrime.sh secondary1: image: mongodb ports: - "27018:27017" environment: - role=secondary volumes: - ./config/r1.conf:/data/config/c.conf secondary2: image: mongodb ports: - "27019:27017" environment: - role=secondary volumes: - ./config/r1.conf:/data/config/c.conf
r0.conf與r1.conf暫時一樣:
#資料檔案夾dbpath=/data/db#記錄檔夾,如果以後台方式運行,必須指定logpathlogpath=/data/log/r.log#以追加而非覆蓋方式寫入日誌logappend=true#連接埠port=27017#以後台方式運行 #fork=true
run.sh:
#!/bin/bash/usr/local/mongodb/bin/mongod -f /data/config/c.conf --replSet "rs0"
runPrime.sh:
#!/bin/bashmongo localhost:27017/admin conf.js
conf.js:
config={_id:"rs0", members:[{_id:0,host:"primary",priority:1}, {_id:1,host:"secondary1",priority:0}, {_id:2,host:"secondary2",priority:0}]}rs.initiate(config)rs.conf()rs.add("secondary1")rs.add("secondary2")
運行過程: 先構建鏡像:
docker build -t mongodb .
啟動容器:
docker-compose up -d
登入主庫,使用指令碼配置,也即運行runPrime.sh來配置複製集:
./runPrime.sh
之後登入即可驗證:
mongo --port 27017
提示符帶有了primary,說明配置成功。 當然可以進一步在主庫寫,從庫讀,但是需要在從庫中使用:
db.setSlaveOk()
才能讀。