【MongoDB+docker】docker 配置 mongodb 复制集
程序员文章站
2024-01-22 22:26:34
...
dockerfile:
docker-compose.yml:
r0.conf与r1.conf暂时一样:
runPrime.sh:
运行过程:
之后登录即可验证:
提示符带有了primary,说明配置成功。
才能读。
#base images
FROM ubuntu:latest
MAINTAINER aaa@qq.com
#install mongodb
RUN apt-get update
RUN apt-get -y install curl
RUN curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz
RUN tar -zxvf mongodb-linux-x86_64-3.0.6.tgz
RUN mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb
RUN export PATH=/usr/local/mongodb/bin:$PATH
ADD ./run.sh /run.sh
RUN chmod 777 /run.sh
#database directory
RUN mkdir -p /data/db
RUN mkdir -p /data/log
RUN touch /data/log/r.log
RUN mkdir -p /data/config
#port
EXPOSE 27017
ENTRYPOINT ["/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
#日志文件夹,如果以后台方式运行,必须指定logpath
logpath=/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/bash
mongo 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()
才能读。