Nginx + php-fpm 性能优化

当nginx日志中出现:
connect() to unix:/var/run/php-fpm/php-fpm.sock failed (11:       Resource temporarily unavailable) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, re      quest: "GET / HTTP/1.0", upstream: "fastcgi://unix:/var/run/php-fpm/php-fpm.sock:", host: "127.0.0.      1"

可以使用ip:port替换unix sock模式(不推荐)
{
vi /etc/php-fpm.d/www.conf
listen = /var/run/php-fpm/php-fpm.sock
to
listen = 127.0.0.1:9002

vi /etc/nginx/conf.d/default.conf
fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
to
fastcgi_pass   127.0.0.1:9002;
}

vi /etc/nginx/nginx.conf
修改 worker_processes 值为cpu核心数*2
...
events {
    use epoll;
    worker_connections  65535;
}
...
keepalive_requests 2048;
keepalive_timeout  30;
...
access_log  /var/log/nginx/access.log  main buffer=64k;
...
sendfile       on;
tcp_nopush     on;
aio            on;
...
client_body_buffer_size 16k;
client_max_body_size 8M;

修改内核网络连接数:
vi /etc/sysctl.conf
add:
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_tw_buckets = 20000

sysctl -p

检查是否生效:
cat /proc/sys/net/core/somaxconn
sysctl -a | grep "netdev_max_backlog"
sysctl -a | grep "tcp_max_syn_backlog"

修改backlog大小,backlog的定义是已连接但未进行accept处理的SOCKET队列大小
vi /etc/php-fpm.d/www.conf
listen.backlog = -1
to
listen.backlog = 8192
...
pm.max_requests = 500
to
pm.max_requests = 1000

当nginx日志中出现:
nginx err.log : accept4() failed (24: Too many open files)
查看当前用户的打开文件数目:
ulimit -n
1024
略少,需增加

vi /etc/nginx/nginx.conf
add line behind line:pid        /var/run/nginx.pid;
worker_rlimit_nofile 655350;

修改系统允许打开文件数、进程数、待处理信号数:
vi /etc/security/limits.conf
*                soft    nofile          655360
*                hard    nofile          655360
*                soft    nproc           655350
*                hard    nproc           655350
*                soft    sigpending      20480
*                hard    sigpending      20480

要使 limits.conf 文件配置生效,必须要确保 pam_limits.so 文件被加入到启动文件中
vi /etc/pam.d/login
session    required     pam_limits.so

修改Nginx请求超时时长:
vi /etc/nginx/conf.d/default.conf
location ~ .php$ {
...
    fastcgi_index  index.php;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 60;
    fastcgi_read_timeout 60;
...
}
vi /etc/php.ini
max_execution_time = 60
vi /etc/php-fpm.d/www.conf
request_terminate_timeout = 60

tail -f /var/log/messages 出现 kernel: nf_conntrack: table full, dropping packet
需要修改状态跟踪表的最大数,理论最大值 CONNTRACK_MAX = RAMSIZE (in bytes) / 16384 / (ARCH / 32)
以64G的64位操作系统为例,CONNTRACK_MAX = 64*1024*1024*1024/16384/2 = 2097152
查看当前值
sysctl net.netfilter.nf_conntrack_max
修改:
vi /etc/sysctl.conf
net.netfilter.nf_conntrack_max = 2097152

reboot