在Ubuntu系统中,LNMP(Linux, Nginx, MySQL, PHP)堆栈的自动重启可以通过多种方式实现。以下是一些常见的方法:
Systemd是现代Linux发行版中用于管理系统服务的初始化系统和服务管理器。你可以为Nginx、MySQL和PHP-FPM创建Systemd服务,并配置它们在失败时自动重启。
sudo nano /etc/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start nginx
sudo systemctl enable nginx
sudo nano /etc/systemd/system/mysql.service
[Unit]
Description=MySQL Community Server
After=network.target
[Service]
ExecStart=/usr/sbin/mysqld
ExecReload=/bin/kill -s HUP $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start mysql
sudo systemctl enable mysql
sudo nano /etc/systemd/system/php7.4-fpm.service
[Unit]
Description=The PHP FastCGI Process Manager
After=syslog.target network.target
[Service]
Type=simple
ExecStart=/usr/sbin/php-fpm7.4 --nodaemonize --fpm-config /etc/php/7.4/fpm/php-fpm.conf
ExecReload=/bin/kill -USR2 $MAINPID
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm
Supervisor是一个进程控制系统,可以用来管理和监控多个进程。
sudo apt-get install supervisor
sudo nano /etc/supervisor/conf.d/nginx.conf
[program:nginx]
command=/usr/sbin/nginx
autostart=true
autorestart=true
stderr_logfile=/var/log/nginx.err.log
stdout_logfile=/var/log/nginx.out.log
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start nginx
sudo supervisorctl start mysql
sudo supervisorctl start php7.4-fpm
你可以编写一个简单的Shell脚本来检查进程是否运行,并在必要时重启它们,然后使用Cron定期运行这个脚本。
sudo nano /usr/local/bin/lnmp_restart.sh
#!/bin/bash
# Check and restart Nginx
if ! pgrep -x "nginx" > /dev/null
then
echo "Nginx is not running. Restarting..."
sudo systemctl start nginx
fi
# Check and restart MySQL
if ! pgrep -x "mysqld" > /dev/null
then
echo "MySQL is not running. Restarting..."
sudo systemctl start mysql
fi
# Check and restart PHP-FPM
if ! pgrep -x "php-fpm" > /dev/null
then
echo "PHP-FPM is not running. Restarting..."
sudo systemctl start php7.4-fpm
fi
sudo chmod +x /usr/local/bin/lnmp_restart.sh
crontab -e
* * * * * /usr/local/bin/lnmp_restart.sh
通过以上方法,你可以确保在Ubuntu系统中LNMP堆栈的各个组件在失败时能够自动重启。