ubuntu

如何在Ubuntu上实现MongoDB的自动化运维

小樊
45
2025-07-21 23:42:11
栏目: 云计算

在Ubuntu上实现MongoDB的自动化运维可以通过以下步骤完成:

环境准备

安装 MongoDB

  1. 更新系统包列表:
    sudo apt update
    
  2. 安装 MongoDB 包管理器:
    sudo apt install software-properties-common
    
  3. 添加 MongoDB 官方源:
    sudo add-apt-repository deb [arch=amd64,arm64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse
    
  4. 更新包列表:
    sudo apt update
    
  5. 安装 MongoDB:
    sudo apt install -y mongodb-org
    
  6. 启动 MongoDB 服务:
    sudo systemctl start mongod
    
  7. 设置 MongoDB 为开机自启:
    sudo systemctl enable mongod
    

配置副本集

  1. 创建配置文件:
    sudo vi /etc/mongod.conf
    
  2. 配置副本集:
    replication:
      replSetName: "rs0"
    
  3. 重启 MongoDB 服务:
    sudo systemctl restart mongod
    
  4. 初始化副本集:
    mongo
    rs.initiate({
      _id: "rs0",
      members: [
        { _id: 0, host: "mongodb-primary:27017" },
        { _id: 1, host: "mongodb-secondary:27017" },
        { _id: 2, host: "mongodb-arbiter:27017" }
      ]
    });
    

启用认证

  1. 修改配置文件:
    sudo vi /etc/mongod.conf
    
  2. 启用认证:
    security:
      authorization: enabled
    
  3. 重启 MongoDB 服务:
    sudo systemctl restart mongod
    
  4. 创建管理员用户:
    use admin
    db.createUser({
      user: "admin",
      pwd: "password",
      roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
    });
    
  5. 重启 MongoDB 服务:
    sudo systemctl restart mongod
    

自动化运维

  1. 编写启动脚本:
    #!/bin/bash
    sudo systemctl start mongod
    
  2. 编写重启脚本:
    #!/bin/bash
    sudo systemctl restart mongod
    
  3. 设置执行权限:
    chmod +x start_mongodb.sh
    chmod +x restart_mongodb.sh
    
  4. 运行脚本:
    ./start_mongodb.sh
    ./restart_mongodb.sh
    

通过以上步骤,您可以在 Ubuntu 系统下轻松实现 MongoDB 的安装、配置和自动化运维。希望本文对您有所帮助。

0
看了该问题的人还看了