在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堆棧的各個組件在失敗時能夠自動重啟。