linux

Linux PHP-FPM负载均衡怎么做

小樊
45
2025-08-01 05:38:07
栏目: 云计算

在Linux环境下,使用PHP-FPM(FastCGI Process Manager)进行负载均衡可以通过多种方式实现。以下是两种常见的方法:

方法一:使用Nginx作为反向代理

  1. 安装Nginx和PHP-FPM: 确保你的服务器上已经安装了Nginx和PHP-FPM。

    sudo apt update
    sudo apt install nginx php-fpm
    
  2. 配置PHP-FPM: 编辑PHP-FPM的配置文件(通常是/etc/php/7.x/fpm/pool.d/www.conf),设置监听地址和端口。

    listen = /run/php/php7.x-fpm.sock
    listen.owner = www-data
    listen.group = www-data
    user = www-data
    group = www-data
    pm = dynamic
    pm.max_children = 5
    pm.start_servers = 2
    pm.min_spare_servers = 1
    pm.max_spare_servers = 3
    

    php7.x替换为你的PHP版本。

  3. 配置Nginx: 编辑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替换为你的网站根目录。

  4. 启动Nginx和PHP-FPM

    sudo systemctl start nginx
    sudo systemctl start php7.x-fpm
    
  5. 配置负载均衡: 如果你有多个PHP-FPM实例,可以在Nginx中配置负载均衡。

    upstream php_backend {
        server unix:/run/php/php7.x-fpm.sock;
        server unix:/run/php/php7.y-fpm.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;
        }
    }
    

    php7.x-fpm.sockphp7.y-fpm.sock替换为你的PHP-FPM实例的socket文件路径。

方法二:使用HAProxy进行负载均衡

  1. 安装HAProxy

    sudo apt update
    sudo apt install haproxy
    
  2. 配置HAProxy: 编辑HAProxy的配置文件(通常是/etc/haproxy/haproxy.cfg),添加后端服务器配置。

    global
        log /dev/log local0
        log /dev/log local1 notice
        daemon
    
    defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5000ms
        timeout client  50000ms
        timeout server  50000ms
    
    frontend http_front
        bind *:80
        default_backend http_back
    
    backend http_back
        balance roundrobin
        server server1 unix:/run/php/php7.x-fpm.sock check
        server server2 unix:/run/php/php7.y-fpm.sock check
    

    server1server2替换为你的PHP-FPM实例的socket文件路径。

  3. 启动HAProxy

    sudo systemctl start haproxy
    

通过以上两种方法,你可以在Linux环境下使用PHP-FPM进行负载均衡。选择哪种方法取决于你的具体需求和环境。

0
看了该问题的人还看了