简介

平时我们使用服务器时会遇到服务不可用的情况,大概率是遇到了死锁导致服务器无法及时响应我们的请求,这时候需要重启解决服务不可用的问题,而且还要排查原因防止再次发生,不过一般情况下个人使用可以省略此步骤(好吧,是不会排查),但重启后需要手动启动应用恢复服务,所以我们需要设置一些脚本让服务器开机自启应用,今天设置如何重启 nginx

修改配置文件

Linux 系统启动后,会调用 /etc/rc.d/rc.local 执行用户脚本,所以我们可以在此设置 nginx 的启动,编辑 /etc/rc.d/rc.local

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/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.

/usr/local/nginx/sbin/nginx

执行命令 chmod +x /etc/rc.d/rc.local 以确保启动时能够正常执行

另附 linux 启动流程:

2-1Q02310563a22.jpg

加入 systemd 服务

systemd 是所有进程之母,负责将 Linux 主机启动到可以做生产性任务的状态。

另一种方法是将 nginx 加入到 systemd 服务

cd /lib/systemd/system/,新建 nginx.service,添加以下内容:

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=nginx service
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

服务运行参数说明

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

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

加入开机自启动

shell
1
systemctl enable nginx

取消开机自启动

shell
1
systemctl disable nginx

服务的启动 / 停止 / 刷新配置文件 / 查看状态

plaintext
1
2
3
4
5
6
7
systemctl start nginx.service          启动nginx服务
systemctl stop nginx.service  停止服务
systemctl restart nginx.service  重新启动服务
systemctl list-units --type=service 查看所有已启动的服务
systemctl status nginx.service 查看服务当前状态
systemctl enable nginx.service 设置开机自启动
systemctl disable nginx.service 停止开机自启动

拓展

根据上述方法,可以制作其他应用的自启动方案,只需提供应用的绝对路径即可

参考文章

Linux /etc/rc.d/rc.local 配置文件用法

Linux 设置 nginx 开机自启动 - 星宇黑雨 - 博客园