【docker安装MongoDB复制集详细步骤】

docker安装MongoDB复制集详细步骤

主节点ip: 192.168.124.122:27017
从节点ip: 192.168.124.129:27017

192.168.124.122  mongo-1
192.168.124.129  mongo-2

1. 配置hosts域名解析

cat >> /etc/hosts << EOF
192.168.124.122 mongo-1
192.168.124.129 mongo-2
EOF

【docker安装MongoDB复制集详细步骤】_第1张图片

2. 创建mongo文件夹

  • 节点1与节点2一致
# 进入opt目录
cd /opt
# 在opt目录下创建文件夹mongo
mkdir /mongo
# 进入mongo目录
cd /opt/mongo
#  在mongo目录下创建文件夹m1,m2
mkdir m1
# 进入m1文件夹
cd /opt/mongo/m1 
# 在m1目录下创建文件夹log,conf,db
mkdir log conf db 
# 给log文件夹授权,log 文件夹需要提权 因为mongodb会创建日志文件
chmod 777 log

cd /opt/mongo/m1/conf 
# 创建配置文件
vim mongod.conf

3. 配置mongod.conf

  • mongod.conf文件的内容如下,将内容复制到mongod.conf中保存并退出
  • 节点1与节点2一致
storage:
  dbPath: /data/db
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:
systemLog:
  destination: file
  logAppend: true
  path: /data/log/mlogs
# where to write logging data.
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
 
 
# how the process runs
security:
  #开启认证
  authorization: enabled
  # 指定keyfile认证
  clusterAuthMode: keyFile 
  keyFile: /data/conf/mongodb.keyfile
  
#operationProfiling:
replication:
  oplogSizeMB: 10240
#复制集名称
  replSetName: rs1
# 进入mongo下的conf文件夹
cd /opt/mongo/conf
# 生成keyfile文件,keyfile文件只生成一次  拷贝到每个节点上使用
openssl rand -base64 736 > /opt/mongo/m1/conf/mongodb.keyfile
# mongodb.keyfile必须授权600和999,否则后续启动不了MongoDB容器
# 给m1的mongodb.keyfile文件授权
chmod 600 mongodb.keyfile
# 给m1的mongodb.keyfile文件授权
chown 999 mongodb.keyfile


# 将mongodb.keyfile文件复制到从节点的conf文件夹下,并授权
# 给从节点的mongodb.keyfile文件授权
chmod 600 mongodb.keyfile
# 给从节点的mongodb.keyfile文件授权
chown 999 mongodb.keyfile

4. 启动mongo容器

# 搜索mongo镜像
docker search mongo
# 拉取镜像
docker pull mongo:5.0.3
# 查看镜像
docker images
# 启动MongoDB 主节点容器
docker run  --network=host --restart always \
--name="m1" \
-v /opt/mongo/m1:/data \
-v /opt/mongo/m1/db:/data/db \
-v /etc/localtime:/etc/localtime \
-d mongo:5.0.3 \
--config /data/conf/mongod.conf

# 启动MongoDB 从节点容器
docker run  --network=host --restart always \
--name="m1" \
-v /opt/mongo/m1:/data \
-v /opt/mongo/m1/db:/data/db \
-v /etc/localtime:/etc/localtime \
-d mongo:5.0.3 \
--config /data/conf/mongod.conf

# 配置防火墙访问接口,如果防火墙是关闭的,则不执行
firewall-cmd  --permanent --zone=public --add-port=27017/tcp
firewall-cmd  --state
firewall-cmd  --reload

# 重启minio
docker restart m1

# docker ps查看启动的容器
docker ps

# 进入容器
docker exec -it m1 bash
# 进入mongo,输入mongo
mongo admin
# 配置集群  "host":"192.168.124.129:27017"为实际服务器的ip
myconf = {"_id":"rs1","members":[{"_id":0,"host":"mongo-1:27017"},{"_id":1,"host":"mongo-2:27017"}]}
# 初始化配置文件
rs.initiate(myconf)   
# 查看集群状态
rs.status()
# 在从节点上想查询需要执行
# MongoDB server version: 5.0.1 已经弃用rs.slaveOk()
# WARNING: slaveOk() is deprecated and may be removed in the next major release. Please use secondaryOk() instead.
# 意思是rs.slaveOk()已经弃用,使用rs.secondaryOk()
rs.secondaryOk()

# 先创建 admin用户 可以操作admin库并且继续创建其他用户
use admin 
db.createUser( {user: "admin",pwd: "123456",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]})
db.auth("admin", "123456")
# 登录admin用户后继续创建用户root权限
db.createUser({user:"root",pwd:"123456",roles:["root"]})
db.auth("root", "123456")
# 创建数据库audit_db  use命令创建数据库,如果有则切换到该数据库,无则创建
use audit_db
# use命令创建数据库,如果有则切换到该数据库,无则创建
db.createCollection("audit_doc")
# 显示数据库
show dbs
# 显示集合

5. 进入容器相关命令

[root@CentOS-7 m1]# docker exec -it m1 bash
root@CentOS-7:/# mongo admin
MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("73fad32c-c7e5-4b0b-b72d-a1b5cc9758ef") }
MongoDB server version: 5.0.3
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
> myconf = {"_id":"rs1","members":[{"_id":0,"host":"mongo-1:27017"},{"_id":1,"host":"mongo-2:27017"}]}
{
        "_id" : "rs1",
        "members" : [
                {
                        "_id" : 0,
                        "host" : "mongo-1:27017"
                },
                {
                        "_id" : 1,
                        "host" : "mongo-2:27017"
                }
        ]
}
> rs.initiate(myconf) 
{ "ok" : 1 }
rs1:SECONDARY> rs.status()
{
        "set" : "rs1",
        "date" : ISODate("2021-11-18T08:03:46.124Z"),
        "myState" : 2,
        "term" : NumberLong(0),
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 2,
        "writeMajorityCount" : 2,
        "votingMembersCount" : 2,
        "writableVotingMembersCount" : 2,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                },
                "lastCommittedWallTime" : ISODate("1970-01-01T00:00:00Z"),
                "appliedOpTime" : {
                        "ts" : Timestamp(1637222617, 1),
                        "t" : NumberLong(-1)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1637222617, 1),
                        "t" : NumberLong(-1)
                },
                "lastAppliedWallTime" : ISODate("2021-11-18T08:03:37.387Z"),
                "lastDurableWallTime" : ISODate("2021-11-18T08:03:37.387Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(0, 0),
        "members" : [
                {
                        "_id" : 0,
                        "name" : "mongo-1:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 170,
                        "optime" : {
                                "ts" : Timestamp(1637222617, 1),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2021-11-18T08:03:37Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 0,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 1,
                        "name" : "mongo-2:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 8,
                        "optime" : {
                                "ts" : Timestamp(1637222617, 1),
                                "t" : NumberLong(-1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1637222617, 1),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2021-11-18T08:03:37Z"),
                        "optimeDurableDate" : ISODate("2021-11-18T08:03:37Z"),
                        "lastHeartbeat" : ISODate("2021-11-18T08:03:46.047Z"),
                        "lastHeartbeatRecv" : ISODate("2021-11-18T08:03:45.817Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 0
                }
        ],
        "ok" : 1
}
rs1:SECONDARY> rs.secondaryOk()
rs1:PRIMARY> use admin 
switched to db admin
rs1:PRIMARY> db.createUser( {user: "admin",pwd: "123456",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]})
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
rs1:PRIMARY> db.auth("admin", "123456")
1
rs1:PRIMARY> db.createUser({user:"root",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
rs1:PRIMARY> db.auth("root", "123456")
1
rs1:PRIMARY> use audit_db
switched to db audit_db
rs1:PRIMARY> db.createCollection("audit_doc")
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1637222699, 1),
                "signature" : {
                        "hash" : BinData(0,"wPlhpziQOHbFcOD8aB9gbPu+Rc8="),
                        "keyId" : NumberLong("7031817639236206595")
                }
        },
        "operationTime" : Timestamp(1637222699, 1)
}
rs1:PRIMARY> show dbs
admin     0.000GB
audit_db  0.000GB
config    0.000GB
local     0.000GB
rs1:PRIMARY> rs.isMaster()
{
        "topologyVersion" : {
                "processId" : ObjectId("619608386bc3246c119d2348"),
                "counter" : NumberLong(6)
        },
        "hosts" : [
                "mongo-1:27017",
                "mongo-2:27017"
        ],
        "setName" : "rs1",
        "setVersion" : 1,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "mongo-1:27017",
        "me" : "mongo-1:27017",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
                "opTime" : {
                        "ts" : Timestamp(1637222777, 1),
                        "t" : NumberLong(1)
                },
                "lastWriteDate" : ISODate("2021-11-18T08:06:17Z"),
                "majorityOpTime" : {
                        "ts" : Timestamp(1637222777, 1),
                        "t" : NumberLong(1)
                },
                "majorityWriteDate" : ISODate("2021-11-18T08:06:17Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2021-11-18T08:06:20.444Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "connectionId" : 5,
        "minWireVersion" : 0,
        "maxWireVersion" : 13,
        "readOnly" : false,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1637222777, 1),
                "signature" : {
                        "hash" : BinData(0,"O6gJHv2zBriDd3owVjkFuTaPMss="),
                        "keyId" : NumberLong("7031817639236206595")
                }
        },
        "operationTime" : Timestamp(1637222777, 1)
}
rs1:PRIMARY> exit
bye
root@CentOS-7:/# exit
exit
[root@CentOS-7 m1]# 
  • 在主数据库中导入数据,查看从数据库,发现数据已经同步
    【docker安装MongoDB复制集详细步骤】_第2张图片

你可能感兴趣的:(数据库,mongodb,docker,数据库)