如何在 Nginx 宕机时自动重启

New*_*ing 18 nginx amazon-web-services

我已将我的应用程序部署到 AWS EC2 上,并且我想实现自动化,如果我重新启动我的实例或当 Nginx Web 服务器关闭时,它会自行重新启动。我真的不知道从哪里开始。

我听说我可以使用 crontab 来安排自动监控,如果它关闭,它可以发送电子邮件警报并重新启动网络服务器。

Dan*_*nin 73

It is a feature of SystemD. Override existing unit file for NGINX by running systemctl edit nginx then paste in:

[Service]
Restart=always
Run Code Online (Sandbox Code Playgroud)

Save.

If NGINX is down due to, e.g. the OOM killer, it will be restarted after dying. If you have a configuration error in NGINX, it will not be restarted, of course.

To verify this configuration. start NGINX service with systemctl start nginx, and verify it is running with systemctl status nginx.

Kill it via pkill -f nginx. Confirm that NGINX is running anyway with systemctl status nginx.

  • @NewbeeCoding 从源代码编译/安装在生产系统上不是一件好事,因为它涉及重新编译升级和将编译软件保存在 prod 中是一种安全风险。为什么不进行打包安装并省去很多麻烦呢?如果您使用编译安装,您需要至少设置启动脚本和日志轮换。有关 SystemD 脚本的示例,请查看 [此处](https://www.nginx.com/resources/wiki/start/topics/examples/systemd/)。我建议复制到`/etc/systemd/system/nginx.service`(`/lib` 是打包的 SystemD 单元文件所在的位置)。 (13认同)

iWi*_*ard 9

Use monit which purpose is to take care of situations like this.

apt install monit

nano /etc/monit/conf.d/nginx.conf
Run Code Online (Sandbox Code Playgroud)

将下面的内容放入此文件并重新启动 monit

check process nginx with pidfile /var/run/nginx.pid
start program = "/usr/sbin/service nginx start"
stop program = "/usr/sbin/service nginx stop"
Run Code Online (Sandbox Code Playgroud)

  • 这一切感觉就像解决了错误的问题。如果这甚至是您必须担心的事情,那么其他事情是错误的,即使失败了,当 systemd 已经能够重新启动服务时,也没有理由增加复杂性。 (13认同)

Jou*_*eek 5

它实际上相当简单

转到 /lib/systemd/system 备份你的 ngnix systemd 单元(以防万一)sudo cp ngnix.service ngnix.service.old

将以下两行添加到 ngnix.service 中的服务块末尾

Restart=on-failure
RestartSec=5s
Run Code Online (Sandbox Code Playgroud)

加载新配置sudo systemctl daemon-reload

测试 - 让我们尝试杀死 ngnix

cat /var/run/nginx.pid会给你PID

sudo kill -9 PID会杀死 nginx

你会发现如果你检查PID,将会有一个不同的PID。如果您没有运行这些行,终止 ngnix 将导致服务器关闭。这只会非正常关闭时触发重新启动


Sim*_*ter 5

你已经有很多如何去做的答案,但我会首先调查发生了什么让它关闭,然后解决这个问题。

当 nginx 崩溃时,所有当前正在运行的请求都将在未知状态下终止——文件传输一半,API 调用未回复。原则上,顶层的应用程序应该处理这个问题,实际上他们很少这样做,但在那个层,它会表现为奇怪和不可复制的行为,给使用服务的人一种不稳定的感觉(这是理所当然的)。