MongoDB使用 Docker 配置单节点副本集

为了快速搭建 MongoDB 副本集开发环境,可以使用 Docker 快速启动一个单节点副本集。

docker-compose 配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
services:
mongodb27017:
hostname: mongodb27017
container_name: mongodb27017
image: mongo:6.0
ports:
- 27018:27017
restart: always
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=yourpassword
command: mongod --bind_ip_all --replSet rs_0 --keyFile /data/mongodb.key
volumes:
- ./data/mongodb/data:/data/db
# - ./data/mongodb/configdb:/data/configdb
networks:
- mongodb-net
entrypoint:
- bash
- -c
- |
openssl rand -base64 128 > /data/mongodb.key
chmod 400 /data/mongodb.key
chown 999:999 /data/mongodb.key
echo 'const isInited = rs.status().ok === 1
if(!isInited){
rs.initiate({
_id: "rs_0",
members: [
{ _id: 0, host: "your_connect_host:27017" }
]
})
}' > /data/initReplicaSet.js
# 启动MongoDB服务
exec docker-entrypoint.sh "$$@" &

# 等待MongoDB服务启动
until mongosh -u root -p yourpassword --authenticationDatabase admin --eval "print('waited for connection')" > /dev/null 2>&1; do
echo "Waiting for MongoDB to start..."
sleep 2
done

# 执行初始化副本集的脚本
mongo -u root -p whfy8888 --authenticationDatabase admin /data/initReplicaSet.js

# 等待docker-entrypoint.sh脚本执行的MongoDB服务进程
wait $$!