Nginx Server – Troubleshooting Slow PHP Load Times

nginxperformanceperformance-monitoringPHP

I have a php application with 815k monthly unique users which loads pretty fast on my dev machine ( around 600 ms for the home page ), and used to load fast on the production server.

I am not a sysadmin, I'm just a developer, so I started to search about diagnosing the server, I followed this flowchart

Although the traffic has increased recently, the server resources seem to be fine.

%Cpu(s):  8.3 us,  2.6 sy,  0.0 ni, 87.1 id,  0.0 wa,  0.0 hi,  0.3 si,  1.7 st

I have plenty of memory available.

After narrowing down the issue, I tried something that gave me interesting results, I copied html source code from my browser and past it to test.html in the production server and it loads in less than 800ms, I take the same html code and past it test.php, and it takes around 6s to loads, both files share the same html code, no database queries are been executed in the files, So I think it has to do with something with my nginx or php configuration.

Here is my nginx configuration:

server {
    listen 80;
    server_name site-name.com;
    root /home/user/site-name.com/public;


    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/site-name.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {

        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 365d;
    }


    location ~ /\.ht {
        deny all;
    }
} 

css, images, html and js files load fast.

PHP fpm configuration

Best Answer

I found the solution, although I have server resources available, but they weren't in use, only 5 was the maximum number of child processes that was allowed to be created. I had a lot memory that wasn't being used. So I edited FPM configuration, in my case, I edited in: /etc/php/7.0/fpm/pool.d/www.conf

I did some calculation for how much memory each process use and how much I have available, and changed these values:

pm = ondemand
pm.max_children = 125
pm.start_servers =
pm.min_spare_servers = 15
pm.max_spare_servers = 25

You can check this tutorial that I followed to learn more about calculating the values.

Now it's working amazingly fast, heaviest page loads under 1s and still have enough memory.