CentOS7.x 配置开机启动项目

  Centos6.x 下版本主要通过service控制启动与关闭,通过chkconfig来设置开机启动项,但是Centos 7.x 版本采用已经Systemd来控制启动与关闭,Systemd 是 Linux 系统中最新的初始化系统(init),它主要的设计目标是克服 sysvinit 固有的缺点,提高系统的启动速度。

  Systemd服务文件以.service结尾,通过yum或者rpm 安装服务的时候会自动在/lib/systemd/system/创建.service 服务配置文件;

下面以nginx为例

1.配置文件说明

[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
        
[Install]
WantedBy=multi-user.target

说明:

  [Unit]:服务的说明
    Description:描述服务
    After:描述服务类别
  [Service]服务运行参数的设置
    Type=forking是后台运行的形式
    ExecStart为服务的具体运行命令
    ExecReload为重启命令
    ExecStop为停止命令
    PrivateTmp=True表示给服务分配独立的临时空间

  [Install]

    WantedBy 这个 unit 本身是附挂在哪一个 target unit 下面的,大多的服务性质的 unit 都是附挂在 multi-user.target 下面。
  注意:

    [Service]的启动、重启、停止命令全部要求使用绝对路径
    [Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3

2.设置开机启动

systemctl enable nginx.service

3.停止开机自启动

systemctl disable nginx.service

4.启动、停止、重新启动、状态服务

systemctl start nginx.service    # 启动
systemctl stop nginx.service   # 停止
systemctl restart nginx.service # 重新启动
systemctl status nginx.service  #状态 

5.查看所有的启动服务项

systemctl list-units --type=service
原文地址:https://www.cnblogs.com/mengyu/p/8257807.html