OS:Ubuntu16.04TLS
MongoDB: 3.4.10
1. 通过apt安装
a. 导入公钥
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
b. 添加MongoDB源
echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/testing multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
c. 安装
sudo apt update
sudo apt install -y mongodb-org
d. 启动、停止、重启
# 启动
sudo service mongod start
# 验证是否启动成功
sudo mongo
# 停止
sudo service mongod stop
# 重启
sudo service mongod restart
e. 卸载
sudo service mongod stop
# 删除package
sudo apt purge mongodb-org*
# 移除数据目录
sudo rm -rf /var/log/mongodb
sudo rm -rf /var/lib/mongdb
2. 手动安装
去MongoDB官方下载地址下载mongodb的.tgz包并解压。
a. 重命名并复制
mv mongodb-linux-x86_64-ubuntu1604-3.4.10 mongodb-3.4.10
sudo cp -r ~/Downloads/mongodb-3.4.10 /usr/local
b. 向PATH添加mongodb的bin目录
# 向~/.profile末尾添加如下内容
export PATH=$PATH:/usr/local/mongodb-3.4.10/bin
# 使修改生效
source ~/.profile
c. 编辑mongod.cnf
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
# 自定义数据存入目录
dbPath: /home/user/mongodb-3.4.10
directoryPerDB: true
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
# 自定义日志存入目录
path: /home/user/mongodb-3.4.10/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
d. 开机启动
创建开机脚本
sudo vim /etc/init.d/mongodb
添加如下内容并保存
#!/bin/sh
### BEGIN INIT INFO
# Provides: mongodb
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: mongodb
# Description: mongo db server
### END INIT INFO
. /lib/lsb/init-functions
PROGRAM=/usr/local/mongodb/bin/mongod
MONGOPID=`ps -ef | grep 'mongod' | grep -v grep | awk '{print $2}'`
test -x $PROGRAM || exit 0
case "$1" in
start)
ulimit -n 3000
log_begin_msg "Starting MongoDB server"
$PROGRAM -f /etc/mongod.conf
log_end_msg 0
;;
stop)
log_begin_msg "Stopping MongoDB server"
if [ ! -z "$MONGOPID" ]; then
kill -15 $MONGOPID
fi
log_end_msg 0
;;
status)
;;
*)
log_success_msg "Usage: /etc/init.d/mongodb {start|stop|status}"
exit 1
esac
exit 0
注册开机脚本
sudo update-rc.d mongodb defaults
# 移除
sudo update-rc.d -f mongodb remove
e. 启动、停止、重启
# 启动
sudo service mongod start
# 验证是否启动成功
sudo mongo
# 停止
sudo service mongod stop
# 重启
sudo service mongod restart