/usr/lib/systemd/system: 安装包相关配置,一般是供应商提供的操作系统资源。通常,只允许包管理工具(yum/dnf/rpm/apt)进行包安装的过程中操作此路径;
/lib/systemd/system: 指向/usr/lib/systemd/system。
/etc/systemd/system:本地配置文件,系统管理员手动软件安装包或脚本放置于此。etc/systemd/system/(系统管理员安装的单元, 优先级更高)

在CentOS 中,实现开机启动程序主要有两种方法:

1、把要启动的程序配置成自定义的系统服务

2、在/etc/rc.local脚本文件中编写启动程序的脚本
方法1:
Centos 系统服务脚本systemctl目录:

/usr/lib/systemd/

有系统(system)和用户(user)之分,
如需要开机没有登陆情况下就能运行的程序,存在系统服务(system)里,即:

#系统服务
/usr/lib/systemd/system/
#用户服务
/usr/lib/systemd/user/

反之,用户登录后才能运行的程序,存在用户(user)里,服务以.service结尾。
每一个服务以.service结尾,一般会分为3部分:[Unit]、[Service]和[Install],就以nginx为例吧,具体内容如下:
这边以nginx开机运行为例:

1.建立服务文件

vim /lib/systemd/system/nginx.service   
 

[Unit]    

Description=nginx    

After=network.target         

[Service]    

Type=forking    

ExecStart=/www/lanmps/init.d/nginx start    

ExecReload=/www/lanmps/init.d/nginx restart    

ExecStop=/www/lanmps/init.d/nginx  stop    

PrivateTmp=true    

[Install]    

WantedBy=multi-user.target   

[Unit]服务的说明
Description:描述服务
After:描述服务类别

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

Type=forking是后台运行的形式

ExecStart为服务的具体运行命令

ExecReload为重启命令

ExecStop为停止命令

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

注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
启动nginx服务:

systemctl start nginx.service

设置开机自启动:

systemctl enable nginx.service

停止开机自启动:

systemctl disable nginx.service

查看服务当前状态:

systemctl status nginx.service

重新启动服务:

systemctl restart nginx.service

查看所有已启动的服务:

systemctl list-units --type=service

方法2
1、/etc/rc.local是/etc/rc.d/rc.local的软链接 ,也就是说他们是同一个文件。

#执行ls -l /etc/rc.local看看。
[root@VM-16-6-centos etc]# ls -l /etc/rc.local
lrwxrwxrwx 1 root root 13 Aug 10 23:31 /etc/rc.local -> rc.d/rc.local

2、rc.local文件的原始内容 执行vi rc.local 查看

[root@VM-16-6-centos etc]# vi rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local

中文意思如下:

# 添加此文件是为了兼容。
# 强烈建议创建自己的systemd服务或udev规则,以便在引导期间运行脚本,而不是使用此文件。
# 与以前版本不同,由于在引导期间并行执行,此脚本不会在所有其他服务之后运行。
# 请注意,必须运行'chmod+x/etc/rc.d/rc.local',以确保在引导期间执行此脚本。

虽然Linux强烈建议采用自定义的系统服务实现开机自启动程序,不过我认为在rc.local中配置开机启动程序也是一个不错的方法,因为rc.local的配置更简单明了,所以仍被广泛的使用。

3、rc.local文件的配置
rc.local本质上是一个shell脚本文件,可以把启动时需要执行的命令写在里面,启动时将按顺序执行。
接下来我们来测试它。
1)在rc.local中添加以下脚本。

/usr/bin/date >> /tmp/date1.log # 把当前时间追加写入到/tmp/date1.log中。
/usr/bin/sleep 10 # 睡眠10秒。
/usr/bin/date >> /tmp/date2.log # 把当前时间追加写入到/tmp/date2.log中。

2)修改/etc/rc.d/rc.local的可执行权限。

chmod +x /etc/rc.d/rc.local

3)重启服务器。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐