You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Homebrew在Intel芯片MacOS部署本地MongoDB副本集

在MacOS上无根目录权限运行MongoDB副本集

核心思路:完全使用用户目录路径替代根目录

所有数据目录、配置文件、密钥文件都放在你有权限的用户主目录(~/)下,避开系统根目录的权限限制。

步骤1:创建所需目录和密钥文件

  1. 创建副本集节点专属数据目录:

    mkdir -p ~/mongodb/replicaset/{rs0-0,rs0-1,rs0-2}
    

    该命令会在用户主目录下生成mongodb/replicaset目录,内部三个子目录分别对应副本集的三个节点。

  2. 生成副本集认证密钥文件(如需启用认证):

    mkdir -p ~/mongodb/
    openssl rand -base64 756 > ~/mongodb/keyfile
    chmod 600 ~/mongodb/keyfile
    

    必须设置密钥文件权限为600,否则MongoDB会拒绝启动。

步骤2:启动副本集节点

打开三个终端窗口,分别启动三个节点:

节点1(端口27017):

mongod --port 27017 --dbpath ~/mongodb/replicaset/rs0-0 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile

节点2(端口27018):

mongod --port 27018 --dbpath ~/mongodb/replicaset/rs0-1 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile

节点3(端口27019):

mongod --port 27019 --dbpath ~/mongodb/replicaset/rs0-2 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile

如果不需要认证,可去掉--keyFile ~/mongodb/keyfile参数。

步骤3:初始化副本集

打开第四个终端窗口,连接到第一个节点:

mongo --port 27017

在MongoDB shell中执行初始化命令:

rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018" },
    { _id: 2, host: "localhost:27019" }
  ]
})

执行rs.status()可查看副本集状态,确认所有节点正常加入。

额外提示

  • 若用Homebrew安装MongoDB,仍可通过--dbpath参数指定用户目录路径,无需依赖默认系统目录。
  • 可将启动命令保存为shell脚本简化操作,比如创建start_rs.sh:
    #!/bin/bash
    mongod --port 27017 --dbpath ~/mongodb/replicaset/rs0-0 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile &
    mongod --port 27018 --dbpath ~/mongodb/replicaset/rs0-1 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile &
    mongod --port 27019 --dbpath ~/mongodb/replicaset/rs0-2 --replSet rs0 --bind_ip localhost --keyFile ~/mongodb/keyfile &
    
    赋予执行权限:chmod +x start_rs.sh,运行./start_rs.sh即可一键启动。

内容的提问来源于stack exchange,提问作者johnmayerfan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:33:29