新部署前可以从仓库(repository)下载 MongoDB 镜像,或者从已有部署中的镜像生成文件:
# 查看当前本地镜像
docker images
# 生成本地镜像文件
docker save <IMAGE ID> -o mongodb_3015.tar
生成 MongoDB 副本集所需的 autokey 文件:
# 建立autokey文件
openssl rand -base64 756 > autokey
# 修改读写模式
chmod 400 autokey
# 在新部署的机器上导入镜像
docker load -i mongodb_3015.tar
docker images
mongodb-deploy.sh 文件内容如下:
#!/bin/bash
mkdir -p /usr/local/docker/mongodb/conf
mkdir -p /usr/local/docker/mongodb/data
cp /root/autokey /usr/local/docker/mongodb/data/
cp /root/mongodb.conf.template /usr/local/docker/mongodb/conf/mongodb.conf
chown -R polkitd:root /usr/local/docker/mongodb/
docker run --name mongo \
-v /usr/local/docker/mongodb/data:/data/db \
-v /usr/local/docker/mongodb/conf:/data/conf \
-p 27017:27017 \
-e TZ=Asia/Shanghai \
-itd a.com:8443/dockerhub/mongo:3.0.15 \
--replSet mvbox_new
mongodb.conf.template 文件内容如下:
port = 27017
logpath = /data/db/mongodb.log
pidfilepath = /data/db/mongodb.pid
dbpath = /data/db/
logappend = true
fork = true
journal = true
directoryperdb = true
auth = true
maxConns = 1000
profile = 1
replSet = mvbox_new
keyFile = /data/db/autokey
# 在所有 MongoDB 副本集机器执行
./mongodb-deploy.sh
在 primary 机器上执行下面的操作。
# 配置副本集
cp /root/rs_initiate.js /usr/local/docker/mongodb/data/
docker exec -it mongo mongo --port 27017 /data/db/rs_initiate.js
rs_initiate.js 文件内容如下:
rs.initiate(
{
_id: "mvbox_new",
version: 1,
members: [
{ _id: 0, host : "172.18.29.56:27017", priority:2 },
{ _id: 1, host : "172.18.29.57:27017", priority:1 },
{ _id: 2, host : "172.18.29.58:27017", priority:1 }
]
}
)
# 创建 admin 用户
docker exec -it mongo mongo --port 27017
use admin;
db.createUser({user : "admin", pwd : "123456", roles: [ { role : "root", db : "admin" } ] });
exit;
# 重新登录,创建更多用户
docker exec -it mongo mongo --port 27017 -u admin -p 123456 admin
use admin
db.createUser({user : "vvmusic_msg", pwd : "123456", roles: [ { role : "dbOwner", db : "vvmusic_msg" } ] });
db.createUser({user : "vvlive", pwd : "123456", roles: [ { role : "dbOwner", db : "vvlive" } ] });
use vvmusic_msg
db.createUser({user : "vvmusic_msg", pwd : "123456", roles: [ { role : "dbOwner", db : "vvmusic_msg" } ] });
use vvlive
db.createUser({user : "vvlive", pwd : "3123456", roles: [ { role : "dbOwner", db : "vvlive" } ] });
exit;
# 验证用户登录
docker exec -it mongo mongo --port 27017 -u admin -p 123456 admin
docker exec -it mongo mongo --port 27017 -u vvlive -p 123456 admin
docker exec -it mongo mongo --port 27017 -u vvlive -p 123456 vvlive
docker exec -it mongo mongo --port 27017 -u vvmusic_msg -p 123456 admin
docker exec -it mongo mongo --port 27017 -u vvmusic_msg -p 123456 vvmusic_msg
# 查看镜像
docker images
# 查看容器
docker ps
# 查看容器详细信息
docker inspect <CONTAINER ID>
# 重启容器
docker restart mongo
# 停止容器
docker stop mongo
# 删除容器
docker rm mongo