在Ubuntu上部署PHP-FPM集群可以提高应用程序的性能和可用性。以下是一个基本的步骤指南,帮助你在Ubuntu上设置一个PHP-FPM集群。
首先,确保你的系统是最新的,并且安装了PHP-FPM。
sudo apt update
sudo apt install php-fpm
默认情况下,PHP-FPM会使用/etc/php/7.x/fpm/pool.d/www.conf
(其中7.x
是你的PHP版本)。你可以根据需要修改这个配置文件。
例如,你可以更改监听端口或添加更多的进程管理器。
; /etc/php/7.x/fpm/pool.d/www.conf
listen = /run/php/php7.x-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
启动PHP-FPM服务并设置为开机自启动。
sudo systemctl start php7.x-fpm
sudo systemctl enable php7.x-fpm
假设你已经安装了Nginx,你可以配置它来使用PHP-FPM处理PHP请求。
编辑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.x-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
确保将example.com
替换为你的域名,并将/var/www/html
替换为你的网站根目录。
启动Nginx服务并设置为开机自启动。
sudo systemctl start nginx
sudo systemctl enable nginx
为了实现高可用性,你可以部署多个PHP-FPM实例。每个实例可以运行在不同的端口或不同的服务器上。
编辑/etc/php/7.x/fpm/pool.d/www.conf
,复制并修改为新的池配置。
; /etc/php/7.x/fpm/pool.d/www1.conf
listen = 127.0.0.1:9001
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
重复上述步骤,创建更多的池配置文件(例如www2.conf
),并更改监听端口。
编辑Nginx配置文件,为每个PHP-FPM实例添加一个location块。
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.x-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.x-fpm@www1.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
启动每个PHP-FPM实例。
sudo systemctl start php7.x-fpm@www1
sudo systemctl start php7.x-fpm@www2
你可以使用Nginx的负载均衡功能来分发请求到不同的PHP-FPM实例。
编辑Nginx配置文件,添加负载均衡配置。
upstream php_backend {
server unix:/run/php/php7.x-fpm.sock;
server unix:/run/php/php7.x-fpm@www1.sock;
server unix:/run/php/php7.x-fpm@www2.sock;
}
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 php_backend;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
重新加载Nginx配置以应用更改。
sudo systemctl reload nginx
通过以上步骤,你可以在Ubuntu上部署一个PHP-FPM集群,并使用Nginx作为反向代理来实现负载均衡和高可用性。