mongodb 安装并设置开机启动

1 配置安装源

cd /etc/yum.repo.d

vi mongodb-org-3.6.repo

yum install mongodb-org

mongodb-org-3.6.repo内容

[mongodb-org-3.6]
name = MongoDB Repository
baseurl = https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck = 1
enabled = 1
gpgkey = https://www.mongodb.org/static/pgp/server-3.6.asc

2 创建用户和数据库

手动启动mongod,使用默认配置文件

mongod --config /etc/mongod.conf

切换至admin库并创建管理用户

$mongo
> use admin
switched to db admin
> db.createUser( {user: "root",pwd: "password",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]})

切换至业务数据库并创建业务数据库用户

> use mydb
switched to db mydb
> db.createUser( {user: "mydbuser", pwd: "mydbpassword", roles: [ { role: "readWrite", db: "mydb" } ]})
Successfully added user: {
	"user" : "landingpage",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "mydb"
		}
	]
}

3 配置mongodb配置文件

vi /etc/mongod.conf
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Listen to local interface only, comment to listen on all interfaces.


security:
  authorization: "enabled"   # disable or enabled


#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

4 配置Service文件

cd /etc/systemd/system

vi mongodb.service 
[Unit]
Description=mongodb
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/bin/mongod --config /etc/mongod.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/bin/mongod --shutdown --config /etc/mongod.conf
PrivateTmp=true
[Install]
WantedBy=multi-user.target

5. 设置启动项

#启动服务
systemctl start mongodb.service
#关闭服务
systemctl stop mongodb.service
#开机启动
systemctl enable mongodb.service

重启后mongodb服务会自动启动

pm2 开机启动

1 启动服务

pm2 start --name nodeapi server/server.js

2 保存配置

pm2 save

3. 设置启动项

pm2 startup

此时在 /etc/systemd/system/ 目录会生成 pm2-root.service

重启后对应的pm2管理的服务会自动启动