CentOS 6安装配置mongodb

安装过程

  1. 服务器下载安装包

    • 下载: curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-4.0.6.tgz;
    • 解压:tar -zxvf mongodb-linux-x86_64-rhel62-4.0.6/;
    • 移动到需要存放的目录下mv mongodb-linux-x86_64-rhel62-4.0.6/ /mnt/mongodb
  2. 配置环境变量:export PATH=/mnt/mongodb/bin:$PATH,直接执行此命令,只会创建出临时的环境变量,即重新断开连接服务器后会失效;

    • 环境变量持久化配置:需要将mongod路径添加到系统路径中,
    1. /etc/profile文件中,添加 export PATH=/mnt/mongodb/bin:$PATH;
    2. 执行source /etc/profile,使系统环境变量立即生效
  3. 验证是否安装成功:mongod --version

    db version v4.0.6
    git version: caa42a1f75a56c7643d0b68d3880444375ec42e3
    OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
    allocator: tcmalloc
    modules: none
    build environment:
        distmod: rhel62
        distarch: x86_64
        target_arch: x86_64

mongod启动配置

1. 创建数据库存放和日志目录

  • 因为MongoDB的数据存储在data目录的db目录下,而该目录在安装过程中并不会自动创建,所以需要手动创建data目录,并在data目录中创建db目录。
  • mongoDB启动默认使用的数据哭存储目录是根目录/data/db;当然也可以在其他目录下创建,然后通过--dbpath来指定;
  • 根目录下创建:mkdir -p /data/db;这里为了后期好查找,就不创建在根目录下,而是放在mongodb目录下/mnt/mongodb/data/db
  • 日志目录创建/mnt/mongodb/logs

2. 配置mongod启动文件

  • /mnt/mongodb/conf下创建配置文件mongod.config:
dbpath=/mnt/mongodb/data   # 数据库存放位置(之前创建的)
logpath=/mnt/mongodb/logs/mongodb.log   # 数据库日志存放位置(之前创建的)
pidfilepath = /mnt/mongodb/tmp/mongodb.pid port=27117 fork=true #后台运行 auth=false # 初次配置先关了权限验证登陆模式 journal=false
#bind_ip=192.168.1.11 #开通远程访问时打开

3. 启动mongod

  • 启动:mongod -f /mnt/mongod/conf/mongod.config
  • 进入数据库管理命令界面:mongo
  • 退出服务,谨慎使用kill直接去杀掉mongodb进程,可以使用db.shutdownServer()关闭.
  • 使用权限方式启动MongoDB,在配置文件中添加:auth=true , 然后启动:mongod -f /usr/local/mongod/etc/mongod.config

4.MongoDB设置为系统服务并且设置开机启动

  • 在服务器的系统服务文件中添加mongod配置:vim /etc/rc.d/init.d/mongod,输入:
start() {
/mnt/mongodb/bin/mongod  --config /mnt/mongodb/conf/mongod.config
}

stop() {
/mnt/mongodb/bin/mongod --config /mnt/mongodb/conf/mongod.config --shutdown
}
case "$1" in
  start)
 start
 ;;

stop)
 stop
 ;;

restart)
 stop
 start
 ;;
  *)
 echo
$"Usage: $0 {start|stop|restart}"
 exit 1
esac
  • 保存并添加脚本执行权限:chmod +x /etc/rc.d/init.d/mongod
  • 现在可以试试使用service mongod [start|stop|restart]来直接管理MongoDB服务.
  • 试试关闭服务:
# service mongod stop
2019-03-10T16:45:22.360+0800 I CONTROL  [main] log file "/usr/local/mongodb/logs/mongodb.log" exists; moved to "/usr/local/mongodb/logs/mongodb.log.2019-03-10T08-45-22".
killing process with pid: 10652
  • 试试开启服务:service mongod start

    about to fork child process, waiting until server is ready for connections.
    forked process: 24291
    child process started successfully, parent exiting

原文地址:https://www.cnblogs.com/shawhe/p/10519204.html