在Ubuntu上配置LNMP(Linux, Nginx, MySQL, PHP)服務器的負載均衡,通常涉及以下幾個步驟:
首先,確保你已經在所有服務器上安裝了Nginx。
sudo apt update
sudo apt install nginx
編輯Nginx的配置文件,通常位于/etc/nginx/nginx.conf
或/etc/nginx/sites-available/default
。
sudo nano /etc/nginx/nginx.conf
在http
塊中添加負載均衡配置:
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的主從復制。
/etc/mysql/mysql.conf.d/mysqld.cnf
,添加以下內容:server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
binlog_do_db = your_database_name
sudo systemctl restart mysql
CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';
FLUSH PRIVILEGES;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
記下File
和Position
的值。
mysqldump -u root -p --all-databases > full-backup.sql
UNLOCK TABLES;
/etc/mysql/mysql.conf.d/mysqld.cnf
,添加以下內容: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_name
sudo systemctl restart mysql
mysql -u root -p < full-backup.sql
CHANGE MASTER TO
MASTER_HOST='master_ip',
MASTER_USER='replicator',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='recorded_log_file_name',
MASTER_LOG_POS=recorded_log_position;
START SLAVE;
確保PHP-FPM在所有服務器上運行,并配置Nginx使用PHP-FPM處理PHP請求。
sudo apt install php-fpm
編輯Nginx配置文件,添加PHP-FPM配置:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根據你的PHP版本調整
}
啟動所有服務器上的Nginx和PHP-FPM服務,并測試負載均衡是否正常工作。
sudo systemctl start nginx
sudo systemctl start php7.4-fpm
訪問你的網站,確保請求被均勻地分發到不同的后端服務器。
通過以上步驟,你可以在Ubuntu上配置一個基本的LNMP負載均衡環境。根據實際需求,你可能需要進一步優化和調整配置。