search
HomeBackend DevelopmentPHP ProblemHow to implement load balancing on php website

php网站实现负载均衡的方法:1、准备好虚拟机;2、通过yum方式安装php;3、加入配置“pid = /usr/local/php-fpm/var/run/php-fpm.pid”;4、通过yum方式安装nginx;5、编写nginx启动脚本,添加配置为“NGINX_SBIN="/usr/local/nginx/sbin/nginx"”。

How to implement load balancing on php website

本教程操作环境:linux5.9.8系统、PHP8.1版、DELL G3电脑

nginx+php 实现代理与负载均衡 (1台nginx,2台php)

实验准备 

3台虚拟机

 192.168.239.136/192.168.239.140/192.168.239.144

1 安装php 192.168.239.140/192.168.239.144

  安装之前先做好这些准备工作(安装基础环境)

 yum -y groupinstall "Development Tools" "Development Libraries"  
 yum install -y epel-release
 yum install -y libxml2-devel.x86_64 openssl-devel.x86_64 bzip2-devel.x86_64 libjpeg-turbo-devel.x86_64 libjpeg-turbo-static.x86_64 libpng-devel.x86_64 libpng-static.x86_64 freetype-devel.x86_64 libstdc++ libstdc++-devel compat-libstdc++-33 libstdc++-static gcc libmcrypt-devel lrzsz gcc gcc-c++  make man vim tree unzip wget curl lua-devel lua-static GeoIP GeoIP-devel  patch libxml2-devel libxslt libxslt-devel gd gd-devel autoconf m4 pcre-devel.x86_64 pcre-static.x86_64 lrzsz ntp libcurl-devel.x86_64 libtool-ltdl-devel.x86_64

下载php源码包到 /usr/local/src  cd /usr/local/src

 解压     cd 解压目录    useradd -s /sbin/nologin php-fpm

./configure --prefix=/usr/local/php   --with-config-file-path=/usr/local/php/etc  --enable-fpm   --with-fpm-user=php-fpm  --with-fpm-group=php-fpm --with-mysql=mysqlnd  --with-libxml-dir  --with-gd   --with-jpeg-dir   --with-png-dir   --with-freetype-dir  --with-iconv-dir   --with-zlib-dir   --with-mcrypt   --enable-soap   --enable-gd-native-ttf   --enable-ftp  --enable-mbstring  --enable-exif  --enable-zend-multibyte   --disable-ipv6   --with-pear   --with-curl 
make && make install
cp php.ini-development /usr/local/php-fpm/etc/php.ini  拷贝配置文件
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm       拷贝启动脚本
mv /usr/local/php-fpm/etc/php-fpm.conf.default  /usr/local/php-fpm/etc/php-fpm.conf  
> /usr/local/php-fpm/etc/php-fpm.conf 
vim !$     加入如下配置
[global]                               
pid = /usr/local/php-fpm/var/run/php-fpm.pid                        error_log = /usr/local/php-fpm/var/log/php-fpm.log     
            [www]                                                                               listen = 192.168.239.140:9000      (IP是php本机IP或者0.0.0.0,不能是127.0.0.1)user = php-fpm group = php-fpmlisten.owner = nobody listen.group = nobody pm = dynamic                               pm.max_children = 50                    pm.start_servers = 20 pm.min_spare_servers = 5 pm.max_spare_servers = 35 pm.max_requests = 500 rlimit_files = 1024 
slowlog = /usr/local/php-fpm/var/slow.logrequest_slowlog_timeout = 1
php_admin_value[open_basedir]=/data/www/:/tmp/
/usr/local/php-fpm/sbin/php-fpm -t
chmod 755 /etc/init.d/php-fpm
/etc/init.d/php-fpm start      netstat -lnpt  查看是否有监听  192.168.239.140:9000
mkdir -p /tmp/tmp
vim /tmp/tmp/index.php       创建动态测试文件,写入如下
    dongtaiqingqiu 1

2.第二台安装php  (安装编译都不变,配置文件IP更改为 192.168.239.144:9000  最后index.php 中dongtaiqingqiu 1改为dongtaiqingqiu2  )

3.安装nginx

下载源码包到 /usr/local/src  cd /usr/local/src

wget http://nginx.org/download/nginx-1.6.2.tar.gz

 解压     cd 解压目录    

yum install -y pcre-devel       
./configure   --prefix=/usr/local/nginx   --with-pcre 
make 
make install

4. 编写nginx启动脚本

vim /etc/init.d/nginx  加入如下配置
#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usr/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start() {
        echo -n $"Starting $prog: "
        mkdir -p /dev/shm/nginx_temp
        daemon $NGINX_SBIN -c $NGINX_CONF
        RETVAL=$?
        echo
        return $RETVAL
}
stop() {
        echo -n $"Stopping $prog: "
        killproc -p $NGINX_PID $NGINX_SBIN -TERM
        rm -rf /dev/shm/nginx_temp
        RETVAL=$?
        echo
        return $RETVAL
}
reload(){
        echo -n $"Reloading $prog: "
        killproc -p $NGINX_PID $NGINX_SBIN -HUP
        RETVAL=$?
        echo
        return $RETVAL
}
restart(){
        stop
        start
}
configtest(){
    $NGINX_SBIN -c $NGINX_CONF -t
    return 0
}
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  reload)
        reload
        ;;
  restart)
        restart
        ;;
  configtest)
        configtest
        ;;
  *)
        echo $"Usage: $0 {start|stop|reload|restart|configtest}"
        RETVAL=1
esac
exit $RETVAL

保存后,执行

chmod a+x /etc/init.d/nginx  或者 chmod 755 !$ 修改权限   
service nginx start          启动nginx

5. 配置反向代理  

> /usr/local/nginx/conf/nginx.conf  
vim /usr/local/nginx/conf/nginx.conf    加入如下配置
user nobody nobody;         
worker_processes 2;            
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
events
{
    use epoll;
    worker_connections 6000;   
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;               
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    '$host "$request_uri" $status'
    '"$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm application/xml;
    include vhosts/*.conf;
}

配置代理

mkdir /usr/local/nginx/conf/vhosts
vi /usr/local/nginx/conf/vhosts/php.conf  加入如下配置
 upstream mysvr {
    #weigth参数表示权值,权值越高被分配到的几率越大
    server 192.168.239.144:9000  weight=2;
    server 192.168.239.140:9000  weight=1;
    }
server
{
    listen 80;
    server_name www.q.com;
    index index.html index.htm index.php;
    root /usr/local/nginx/html;
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass mysvr;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /tmp/tmp$fastcgi_script_name;
    }
}
/usr/local/nginx/sbin/nginx -t   检测配置文件
/usr/local/nginx/sbin/nginx -s reload  (直接重新加载配置,不需要重启)
vim /usr/local/nginx/html/1.html     创建静态测试文件,写入
    jingtaifangwen

设置本地解析

修改windons hosts(地址 c:\windows\system32\drivers\etc\hosts)记事本打开,最下面添加一行配置

192.168.239.136 www.q.com

测试:最好用谷歌浏览器 (如下显示 代理成功)

   访问  www.q.com   显示的是nginx 默认页

   访问  www.q.com/.html   显示的jingtaifangwen

   访问  www.q.com/index.php  多刷新几次  会显示 dongtaifangwen1 一次 dongtaifangwen2 两次

推荐学习:《PHP视频教程

The above is the detailed content of How to implement load balancing on php website. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function