1、创建脚本文件
touch /etc/init.d/mongodb.sh
2、添加启动脚本内容
先执行
vi /etc/init.d/mongodb.sh
将以下内容添加到mongodb.sh文件中:
#!/bin/bash
#
# MongoDB startup script
#### BEGIN INIT INFO
# Provides: mongodb
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: MongoDB
# Description: MongoDB Database Server
### END INIT INFO# Path to MongoDB installation
MONGODB_HOME=/usr/local/mongodb# MongoDB configuration file
MONGODB_CONF=/usr/local/mongodb/etc/mongod.conf# MongoDB log file
MONGODB_LOG=/usr/local/mongodb/logs/mongodb.log# Start MongoDB
start() {echo "Starting MongoDB..."$MONGODB_HOME/bin/mongod --config $MONGODB_CONF >> $MONGODB_LOG 2>&1 &
}# Stop MongoDB
stop() {echo "Stopping MongoDB..."$MONGODB_HOME/bin/mongod --shutdown --config $MONGODB_CONF >> $MONGODB_LOG 2>&1
}# Restart MongoDB
restart() {stopstart
}case "$1" instart)start;;stop)stop;;restart)restart;;*)echo "Usage: $0 {start|stop|restart}"exit 1
esacexit 0
3、设置脚本权限
chmod +x /etc/init.d/mongodb.sh
4、创建启动链接
ln -s /etc/init.d/mongodb.sh /etc/rc.d/
5、添加到开机启动服务
chkconfig --add mongodb.sh
6、设置开启自启动
chkconfig mongodb.sh on
7、启动MongoDB服务
service mongodb.sh start
8、验证重启是否启动
首先重启电脑,再执行
ps aux | grep mongod
输出如下界面
说明设置成功