centos 设置systemctl自启服务文件

方式一

建立服务文件

vim /usr/lib/systemd/system/mongodb.service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit] 

Description=mongodb
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/mongodb/bin/mongod -config /usr/local/mongodb/bin/mongodb.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/local/mongodb/bin/mongod --shutdown -config /usr/local/mongodb/bin/mongodb.conf
PrivateTmp=true

[Install]
WantedBy=multi-user.target

文件内容解释

Description:描述服务

After:描述服务类别

[Service]服务运行参数的设置

Type=forking是后台运行的形式

ExecStart为服务的具体运行命令

ExecReload为重启命令

ExecStop为停止命令

PrivateTmp=True表示给服务分配独立的临时空间

注意:启动、重启、停止命令全部要求使用绝对路径

[Install]服务安装的相关设置,可设置为多用户

设置开机自启动

任意目录下执行

systemctl enable xxx.service

其他命令

启动服务

systemctl start xxxx.service

设置开机自启动

systemctl enable xxxx.service

停止开机自启动

systemctl disable xxxx.service

查看服务当前状态

systemctl status xxx.service

重新启动服务

systemctl restart xxx.service

查看所有已启动的服务

systemctl list-units –type=service

CentOS7.0中systemctl启动关闭服务的用法

systemctl是主要的工具,它融合之前service和chkconfig的功能于一体。可以使用它永久性或只在当前会话中启用/禁用服务。
systemctl可以列出正在运行的服务状态
systemd-cgls以树形列出正在运行的进程,它可以递归显示控制组内容。

1
2
3
4
5
6
7
8
9
10
11
启动/关闭、启用/禁用服务:
启动一个服务:systemctl start postfix.service
关闭一个服务:systemctl stop postfix.service
重启一个服务:systemctl restart postfix.service
显示一个服务的状态:systemctl status postfix.service

在开机时启用一个服务:systemctl enable postfix.service
在开机时禁用一个服务:systemctl disable postfix.service
查看服务是否开机启动:systemctl is-enabled postfix.service;echo $?

查看已启动的服务列表:systemctl list-unit-files|grep enabled

说明:启用服务就是在当前“runlevel”的配置文件目录/etc/systemd/system/multi-user.target.wants/里,建立/usr/lib/systemd/system里面对应服务配置文件的软链接;禁用服务就是删除此软链接

方式二

先在/etc/rc.d/init.d下新建文件 mongod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/sh
#
#chkconfig: 2345 80 90
#description: mongodb

if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi

start() {
/usr/local/mongodb/bin/mongod -config /usr/local/mongodb/bin/mongodb.conf
}

stop() {
/usr/local/mongodb/bin/mongod -config /usr/local/mongodb/bin/mongodb.conf --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

chkconfig –add mongod

chkconfig –level 345 mongod on

chkconfig –list mongod

service mongod start

之后就可以开始使用service mongod start|stop|restart 管理mongodb服务了。