在Ubuntu上實現LNMP(Linux, Nginx, MySQL, PHP)高可用性,可以通過以下幾個步驟來實現:
使用Nginx作為反向代理和負載均衡器,將流量分發到多個后端服務器。
sudo apt update
sudo apt install nginx
編輯Nginx配置文件 /etc/nginx/nginx.conf
或創建一個新的配置文件 /etc/nginx/conf.d/load_balancer.conf
:
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
使用MySQL的主從復制或MySQL Cluster來實現高可用性。
配置主服務器:
編輯 /etc/mysql/mysql.conf.d/mysqld.cnf
:
[mysqld]
server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
binlog_do_db = your_database
配置從服務器:
編輯 /etc/mysql/mysql.conf.d/mysqld.cnf
:
[mysqld]
server-id = 2
relay_log = /var/log/mysql/mysql-relay-bin.log
log_bin = /var/log/mysql/mysql-bin.log
binlog_do_db = your_database
重啟MySQL服務:
sudo systemctl restart mysql
設置主從復制: 在主服務器上創建一個用于復制的用戶,并獲取二進制日志位置:
CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';
FLUSH PRIVILEGES;
SHOW MASTER STATUS;
在從服務器上配置復制:
CHANGE MASTER TO
MASTER_HOST='master_ip',
MASTER_USER='replicator',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=107;
START SLAVE;
使用PHP-FPM的多實例和負載均衡來實現高可用性。
sudo apt install php-fpm
編輯 /etc/php/7.4/fpm/pool.d/www.conf
:
listen = /run/php/php7.4-fpm.sock
listen.owner = www-data
listen.group = www-data
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
編輯Nginx配置文件 /etc/nginx/sites-available/default
:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
使用監控工具如Prometheus和Grafana來監控系統狀態,并設置自動故障轉移機制。
sudo apt install prometheus grafana
根據官方文檔配置Prometheus和Grafana,監控系統資源、MySQL狀態、Nginx和PHP-FPM的性能。
通過以上步驟,你可以在Ubuntu上實現LNMP的高可用性。確保定期備份數據,并測試故障轉移機制以確保系統的穩定性。