Docker搭建MongoDB 4.0副本集

环境:

系统版本:CentOS 7.5
内核:4.18.7-1.el7.elrepo.x86_64
Docker-ce: 18.06
MongoDB: 4.0.3

宿主机IP:192.168.1.1
MongoDB1端口:30001
MongoDB2端口:30002
MongoDB3端口:30003

一、安装docker、docker-compose

wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

yum install -y docker-ce python-pip

mkdir /etc/docker/
cat << EOF > /etc/docker/daemon.json
{   "registry-mirrors": ["https://registry.docker-cn.com"],
    "live-restore": true,
    "default-shm-size": "128M",
    "max-concurrent-downloads": 10,
    "oom-score-adjust": -1000,
    "debug": false
}
EOF

pip install docker-compose

systemctl enable docker
systemctl start docker

二、创建副本集所需的key

#创建一个volume,将创建的key文件复制至volume中
#400权限是要保证安全性,否则mongod启动会报错
#999用户是容器中的mongod用户

cd && mkdir mongod && cd mongod
openssl rand -base64 756 > mongo.key
docker volume create mongod_mongo_key
MONGO_KEY_DIR=`docker volume inspect mongod_mongo_key | grep Mount | sed -r ‘s#.*"(.*)",$#\1#‘`
cp mongo.key $MONGO_KEY_DIR
chmod 400 $MONGO_KEY_DIR/mongo.key
chown 999.999 $MONGO_KEY_DIR/mongo.key

mkdir /data/mongo/mongdb{1..3} -pv

三、创建docker-compose文件

#映射/data/mongo/mongdb{1,2,3}目录到容器里,将数据持久化到磁盘
#映射出三个端口,以便外部用户连接
#MONGO_INITDB_ROOT_USERNAME:管理员用户的账号
#MONGO_INITDB_ROOT_PASSWORD:管理员用户的密码

cat << EOF > docker-compose.yaml
version: "3.7"
services:
  mongodb1:
    image: mongo:4.0.3
    container_name: mongodb1
    networks:
      - mongodb
    ports:
      - "30001:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=123456x
    volumes:
      - /data/mongo/mongdb1:/data/db
      - mongo_key:/mongo
    command: ["mongod","--replSet","BigBoss","--keyFile","/mongo/mongo.key","--directoryperdb"]

  mongodb2:
    image: mongo:4.0.3
    container_name: mongodb2
    networks:
      - mongodb
    ports:
      - "30002:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=123456
    volumes:
      - /data/mongo/mongdb2:/data/db
      - mongo_key:/mongo
    command: ["mongod","--replSet","BigBoss","--keyFile","/mongo/mongo.key","--directoryperdb"]

  mongodb3:
    image: mongo:4.0.3
    container_name: mongodb3
    networks:
      - mongodb
    ports:
      - "30003:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=123456
    volumes:
      - /data/mongo/mongdb3:/data/db
      - mongo_key:/mongo
    command: ["mongod","--replSet","BigBoss","--keyFile","/mongo/mongo.key","--directoryperdb"]

networks:
  mongodb:
    driver: bridge
    name: mongodb

volumes:
  mongo_key:
EOF

四、启动副本集

#副本集群成员的IP地址必须要让客户的也能解析这个IP,不然使用集群方式连接数据库时,无法连接!!!
#若是在阿里云ECS上搭建副本集,想要让公网的客户端能够连接,必须要填ECS的公网IP!!!

#启动三个容器,并使他们后台运行

docker pull mongo:4.0.3
docker-compose up -d

#连接30001端口上的容器,开始配置集群

mongo -port 30001 -uroot -p123456 --authenticationDatabase admin

#三节点,其中一个为投票节点,并隐藏
#注意host的IP地址,一定要让客户端也能连接所有的地址
#_id的值为--replSet参数后的字符串

rs.initiate(
{
  _id: "BigBoss",
  version: 1,
  protocolVersion: 1,
  writeConcernMajorityJournalDefault: true,
  members: [
    {
      _id: 0,
      host: "192.168.1.1:30001",
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 66,
      tags: {
        BigBoss: "YES"
      },
      slaveDelay: 0,
      votes: 1
    },
    {
      _id: 1,
      host: "192.168.1.1:30002",
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 55,
      tags: {
        BigBoss: "NO"
      },
      slaveDelay: 0,
      votes: 1
    },
    {
      _id: 2,
      host: "192.168.1.1:30003",
      arbiterOnly: true,
      buildIndexes: true,
      hidden: true,
      priority: 0,
      tags: {
      },
      slaveDelay: 0,
      votes: 1
    }
  ],
  settings: {
    chainingAllowed : true,
  }
}
)

####################################################
[[email protected] mongod]#mongo -port 30001 -uroot -p123456 --authenticationDatabase admin
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:30001/
Implicit session: session { "id" : UUID("a196085a-a142-450f-9eab-a0fc5a58c43b") }
MongoDB server version: 4.0.3
Server has startup warnings:
2018-10-09T10:15:20.474+0000 I CONTROL  [initandlisten]
2018-10-09T10:15:20.474+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is ‘always‘.
2018-10-09T10:15:20.474+0000 I CONTROL  [initandlisten] **        We suggest setting it to ‘never‘
2018-10-09T10:15:20.474+0000 I CONTROL  [initandlisten]
---
Enable MongoDB‘s free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>
>
> rs.initiate(
... {
...   _id: "BigBoss",
...   version: 1,
...   protocolVersion: 1,
...   writeConcernMajorityJournalDefault: true,
...   members: [
...     {
...       _id: 0,
...       host: "192.168.1.1:30001",
...       arbiterOnly: false,
...       buildIndexes: true,
...       hidden: false,
...       priority: 66,
...       tags: {
...     BigBoss: "YES"
...       },
...       slaveDelay: 0,
...       votes: 1
...     },
...     {
...       _id: 1,
...       host: "192.168.1.1:30002",
...       arbiterOnly: false,
...       buildIndexes: true,
...       hidden: false,
...       priority: 55,
...       tags: {
...     BigBoss: "NO"
...       },
...       slaveDelay: 0,
...       votes: 1
...     },
...     {
...       _id: 2,
...       host: "192.168.1.1:30003",
...       arbiterOnly: true,
...       buildIndexes: true,
...       hidden: true,
...       priority: 0,
...       tags: {
...       },
...       slaveDelay: 0,
...       votes: 1
...     }
...   ],
...   settings: {
...     chainingAllowed : true,
...   }
... }
... )
{ "ok" : 1 }
BigBoss:SECONDARY>
BigBoss:SECONDARY>
BigBoss:SECONDARY>
BigBoss:SECONDARY>
BigBoss:PRIMARY>
BigBoss:PRIMARY>

#现在30001端口的容器已经是PRIMARY了

五、测试

#停止PRIMARY的容器

docker ps -a
docker stop mongodb1

#######################################################################################
[[email protected] mongod]#docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
62f42e2aee19        mongo:4.0.3         "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        0.0.0.0:30003->27017/tcp   mongodb3
735b8d8a2bcf        mongo:4.0.3         "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        0.0.0.0:30001->27017/tcp   mongodb1
27ebcebde77e        mongo:4.0.3         "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes       0.0.0.0:30002->27017/tcp   mongodb2
[[email protected] mongod]#docker stop mongodb1
mongodb1
[[email protected] mongod]#docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                      NAMES
62f42e2aee19        mongo:4.0.3         "docker-entrypoint.s…"   6 minutes ago       Up 6 minutes               0.0.0.0:30003->27017/tcp   mongodb3
735b8d8a2bcf        mongo:4.0.3         "docker-entrypoint.s…"   6 minutes ago       Exited (0) 2 seconds ago                              mongodb1
27ebcebde77e        mongo:4.0.3         "docker-entrypoint.s…"   6 minutes ago       Up 6 minutes              0.0.0.0:30002->27017/tcp   mongodb2
[[email protected] mongod]#

#连接端口为30002的容器

mongo -port 30002 -uroot -p123456 --authenticationDatabase admin

#查看集群状态
rs.status()

#######################################################################################

[[email protected] mongod]#mongo -port 30002 -uroot -p123456 --authenticationDatabase admin
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:30002/
Implicit session: session { "id" : UUID("7a83559d-84e3-4c89-93dd-1947d40c4837") }
MongoDB server version: 4.0.3
Server has startup warnings:
2018-10-09T10:20:50.944+0000 I CONTROL  [initandlisten]
2018-10-09T10:20:50.944+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is ‘always‘.
2018-10-09T10:20:50.944+0000 I CONTROL  [initandlisten] **        We suggest setting it to ‘never‘
2018-10-09T10:20:50.945+0000 I CONTROL  [initandlisten]
---
Enable MongoDB‘s free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

BigBoss:PRIMARY>
BigBoss:PRIMARY>
BigBoss:PRIMARY> rs.status()
{
    "set" : "BigBoss",
    "date" : ISODate("2018-10-09T10:22:16.104Z"),
    "myState" : 1,
    "term" : NumberLong(2),
    "syncingTo" : "",
    "syncSourceHost" : "",
    "syncSourceId" : -1,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(1539080483, 1),
            "t" : NumberLong(1)
        },
        "readConcernMajorityOpTime" : {
            "ts" : Timestamp(1539080483, 1),
            "t" : NumberLong(1)
        },
        "appliedOpTime" : {
            "ts" : Timestamp(1539080528, 1),
            "t" : NumberLong(2)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1539080528, 1),
            "t" : NumberLong(2)
        }
    },
    "lastStableCheckpointTimestamp" : Timestamp(1539080483, 1),
    "members" : [
        {
            "_id" : 0,
            "name" : "192.168.1.1:30001",
            "health" : 0,
            "state" : 8,
            "stateStr" : "(not reachable/healthy)",
            "uptime" : 0,
            "optime" : {
                "ts" : Timestamp(0, 0),
                "t" : NumberLong(-1)
            },
            "optimeDurable" : {
                "ts" : Timestamp(0, 0),
                "t" : NumberLong(-1)
            },
            "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
            "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
            "lastHeartbeat" : ISODate("2018-10-09T10:22:15.296Z"),
            "lastHeartbeatRecv" : ISODate("2018-10-09T10:21:26.296Z"),
            "pingMs" : NumberLong(0),
            "lastHeartbeatMessage" : "Error connecting to 192.168.1.1:30001 :: caused by :: Connection refused",
            "syncingTo" : "",
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "",
            "configVersion" : -1
        },
        {
            "_id" : 1,
            "name" : "192.168.1.1:30002",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 86,
            "optime" : {
                "ts" : Timestamp(1539080528, 1),
                "t" : NumberLong(2)
            },
            "optimeDate" : ISODate("2018-10-09T10:22:08Z"),
            "syncingTo" : "",
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "could not find member to sync from",
            "electionTime" : Timestamp(1539080497, 1),
            "electionDate" : ISODate("2018-10-09T10:21:37Z"),
            "configVersion" : 1,
            "self" : true,
            "lastHeartbeatMessage" : ""
        },
        {
            "_id" : 2,
            "name" : "192.168.1.1:30003",
            "health" : 1,
            "state" : 7,
            "stateStr" : "ARBITER",
            "uptime" : 85,
            "lastHeartbeat" : ISODate("2018-10-09T10:22:15.275Z"),
            "lastHeartbeatRecv" : ISODate("2018-10-09T10:22:14.994Z"),
            "pingMs" : NumberLong(0),
            "lastHeartbeatMessage" : "",
            "syncingTo" : "",
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "",
            "configVersion" : 1
        }
    ],
    "ok" : 1,
    "operationTime" : Timestamp(1539080528, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1539080528, 1),
        "signature" : {
            "hash" : BinData(0,"f+D+XukeDBrkwdiZD5AvUJkHg3M="),
            "keyId" : NumberLong("6610298923057676289")
        }
    }
}
BigBoss:PRIMARY>

原文地址:http://blog.51cto.com/bigboss/2296445

时间: 2024-10-31 15:02:45

Docker搭建MongoDB 4.0副本集的相关文章

MongoDB 3.0副本集搭建

环境配置 MongoDB安装 下载yum源配置 wget https://repo.mongodb.org/yum/redhat/mongodb-org-3.0.repo  mv mongodb-org-3.0.repo  /etc/yum.repos.d/ 安装mongodb yum -y install mongodb-org 修改mongodb配置文件 # 修改监听地址为0.0.0.0 net:   port: 27017   bindIp: 0.0.0.0 # 修改副本集配置 repli

mongoDB主从和副本集群配置

mongoDB主从和副本集群配置 Mongodb是时下流行的NoSql数据库(MongoDB是一个基于分布式文件存储的数据库),它的存储方式是文档式存储,并不是Key-Value形式.   优势: 快速!(当然,这和具体的应用方式有关,通常来说,它比一般的关系型数据库快5位左右.) 很高的可扩展性–轻轻松松就可实现PB级的存储(但是可能我们并不需要PB级的存储,10TB可能就够了) 他有一个很好的 replication 模式 (replica sets) 有很完善的Java API 他的存储格

【六】MongoDB管理之副本集

一.复制介绍 所谓的复制就是在多个主机之间同步数据的过程. 1.数据冗余及可用性 复制技术提供数据冗余及可用性,在不同的数据库服务器上使用多个数据副本,复制技术防止单个数据库服务器出现数据故障而出现数据丢失.通过设置从库,你能在上面进行灾难切换.数据备份.报表服务等.在某些应用场景下,你还能提高读的能力,客户端通过将读和写请求分发到不同的服务器上面. 2.MongoDB复制技术 副本集是一组共享相同数据集的mongod实例.当所有写请求发向主库,而其他从库从主库上应用这些操作,以保证所有成员数据

mongodb3.0副本集搭建补充~~非admin数据库的用户权限

之前有搭建mongodb3.0的副本集,不过当时直接使用的admin数据库,用户也是直接给的root. 链接:http://blog.csdn.net/tuzongxun/article/details/51723259 最近想要把数据移到非admin数据库上,便重新以非admin库创建用户,过程大致和之前的一样,但创建用户的时候还是遇到了一些问题,主要是在用户角色和权限上. 我搭建过程中参考了下边的用户权限相关的博客: http://blog.csdn.net/tuzongxun/articl

mongodb安装和副本集的搭建

CentOS 编译安装 Mongodb Centos 7.0 + Mongodb 2.6.6 (实测 笔记 ) 环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G,双网卡) 系统版本:CentOS-7.0-1406-x86_64-DVD.iso安装步骤: 1.安装基本软件包 [[email protected] ~]# yum install vim wget lsof gcc gcc-c++ bzip2 -y [[email protected] ~]# yum in

Centos6.6搭建mongodb3.2.6副本集分片

1.环境准备centos6.6 x64 3台192.168.0.23192.168.0.24192.168.0.201 2.集群规划每个机器同时启动mongos.config server .shard0.shard2.shard3,config server得ip端口分别为:192.168.0.23:1111,192.168.0.24:1111,192.168.0.201:1111mongos得ip端口分别为:192.168.0.23:2222,192.168.0.24:2222,192.16

基于Docker搭建ActiveMQ的高可用集群

最近刚开始玩Docker和ActiveMQ刚好学习到ActiveMQ集群的搭建,就将其记录了下来给有需要的人,也可以跟大家交流交流. 这里先感谢慕课网和http://blog.csdn.net/lifetragedy/article/details/51869032,在学习ActiveMQ有很大的帮助. 一.docker坏境的搭建. 这里重点不是docker,而是基于docker搭建的ActiveMQ集群,docker了解的也可以参考http://www.docker.org.cn/.     

Ubuntu16.04搭建MongoDB3.4.3 副本集 开启认证模式

上一篇文档讲述的是如何搭建mongodb副本集 这一篇讲述启用auth 一.为了方便启动,我们在Mongodb目录下新建conf目录,用于保存mongodb的配置文件 #进入mongod目录 cd mongodb/ #创建conf目录 mkdir conf #新增mongodb.conf vim mongodb.conf写入如下内容---------------------------------------: #日志文件位置 logpath=/data/bigdata/software/mon

修改mongodb3.0副本集用户密码遇到的坑

最近公司对项目安全方面的问题很是重视,进行了多次各种安全漏洞的扫描,于是乎就扫到了mongodb弱口令的问题. 在项目部署初期,因为大家对这个都不是特别重视,大概是因为觉得反正是内网项目吧,所以mongodb数据库的用户名和密码就都是admin. 这次扫到弱口令之后,要求解决这个问题,于是任务便分到了我的头上. 遵循强口令的标准,我把admin改成了由大写字母.小写字母.数字和特殊字符共同组成的密码,但是在更改的过程中却并不像想象的那么顺利,其中遇到的问题我称之为mongodb副本集密码的一些坑