ubuntu

Ubuntu MongoDB集群怎么搭建

小樊
38
2025-06-29 17:46:18
栏目: 云计算

在Ubuntu上搭建MongoDB集群涉及多个步骤,包括安装、配置、初始化等。以下是一个基本的指南:

准备工作

  1. 硬件资源:准备3-5台虚拟机,其中1-3台为管理节点,2台为工作节点。为了高可用性,可以部署3个及以上的奇数节点。
  2. 软件环境
    • 操作系统:推荐使用Ubuntu 18.04或更高版本。
    • MongoDB版本:选择稳定且支持相关特性的版本,如MongoDB 4.4及以上版本。

安装MongoDB

  1. 更新包列表
    sudo apt update
    
  2. 安装MongoDB
    sudo apt install -y mongodb-org
    

配置MongoDB实例

  1. 创建数据目录
    sudo mkdir -p /data/db
    sudo mkdir -p /var/log/mongodb
    sudo mkdir -p /etc/mongodb
    
  2. 配置config server副本集: 编辑/etc/mongodb/config.conf文件:
    systemLog:
      destination: file
      logAppend: true
      path: /var/log/mongodb/config.log
    storage:
      dbPath: /data/db
      journal:
        enabled: true
    net:
      port: 27019
      bindIp: 0.0.0.0
    
    启动config server:
    sudo mongod --config /etc/mongodb/config.conf
    
    初始化config server副本集:
    mongo --host <config_server_ip>:27019
    rs.initiate({
      _id: "configRs",
      configsvr: true,
      members: [{_id: 0, host: "<config_server_ip>:27019"}, {_id: 1, host: "<config_server_ip>:27019"}, {_id: 2, host: "<config_server_ip>:27019"}]
    })
    
  3. 配置shard分片副本集: 编辑/etc/mongodb/shard1.conf文件:
    systemLog:
      destination: file
      logAppend: true
      path: /var/log/mongodb/shard1.log
    storage:
      dbPath: /data/shard1
      journal:
        enabled: true
    net:
      port: 27001
      bindIp: 0.0.0.0
    
    启动shard1:
    sudo mongod --config /etc/mongodb/shard1.conf
    
    初始化shard1副本集:
    mongo --host <shard1_node_ip>:27001
    rs.initiate({
      _id: "shard1Rs",
      members: [{_id: 0, host: "<shard1_node_ip>:27001"}, {_id: 1, host: "<shard1_node_ip>:27001"}, {_id: 2, host: "<shard1_node_ip>:27001", arbiterOnly: true}]
    })
    

配置mongos路由器

编辑/etc/mongodb/mongos.conf文件:

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongos.log
storage:
  dbPath: /data/mongos
net:
  port: 27017
  bindIp: 0.0.0.0
sharding:
  configDB: configRs/<config_server_ip>:27019,<config_server_ip>:27019,<config_server_ip>:27019

启动mongos:

sudo mongos --configdb <config_server_ip>:27019,<config_server_ip>:27019,<config_server_ip>:27019 --port 27017

添加分片到集群

在mongos shell中添加分片:

sh.addShard("<shard1_rs_host>:27001")
sh.addShard("<shard2_rs_host>:27002")

验证集群状态

使用以下命令验证集群状态:

sh.status()

通过以上步骤,您可以在Ubuntu上搭建一个基本的MongoDB分片集群。根据实际需求,您可能需要调整配置和增加更多的节点。

0
看了该问题的人还看了