Optimizing Tips and Tricks Nginx and php7.0-FPM Ubuntu 16.04 LTS
Optimizing Tips and Tricks Nginx and php7.0-FPM Ubuntu 16.04 LTS
– Find out where is Nginx Configuration Files.
When Nginx install from deb package we will observe commonly Nginx configuration files under the folder are fixed like /etc/nginx path.
## Main Nginx config file ## /etc/nginx/nginx.conf ## Virtualhost Nginx configuration files on ## /etc/nginx/sites-available/ /etc/nginx/sites-enabled/ ## Other Nginx config files on (if needed) ## /etc/nginx/conf.d/
– Rule of Nginx worker_processes and worker_connections.
max_clients = worker_processes * worker_connections
Normally 1000 concurrent connection / per single server is consider good one, but on the other hand, sometime server disks might be slow, and it is because the Nginx is locked on I/O operations. To avoid locking try these given example and the following setup: one worker_process / per processor core, like:
Worker Processes:
worker_processes [number of processor cores/ auto];
Noe again check how many processor has in machine.
cat /proc/cpuinfo |grep processor processor : 0 processor : 1 processor : 2 processor : 3
So, In this case we have 4 cores and worker_processes and final setup could be following:
worker_processes 4;
Personally,I stick with 1024 worker connections, because I have no reason to raise this value. But if example 4096 connections per second is not sufficient according to you then it is possible that you can try to double it and set 2048 connections per process.
worker_connections 1024;
Now I have find some configurations where server admins are using Apache more and try if I set Nginx worker_processes to 50 and worker_connections to 20000 then my server can handle all traffic once what we recieve monthly yes but it’s not true. It’s just to waste your resources and might cause issue for the few serious problems.
Important: Hide Nginx Server Tokens / Hide Nginx version number
This is more good for the security purpose and hide server tokens / hide Nginx version number, especially, if run some old-fashioned version of Nginx. This is very simple to do it just set server_tokens off under http/server/location section, like:
server_tokens off;
– Need to find out how many Nginx Request / Upload Max Body Size (client_max_body_size)
If you want to give permission to the users upload something or upload personally over the HTTP then you should need to increase the post size. Let done with the client_max_body_size value which goes under http/server/location section. On default it can be 1 Mb, but it can also set example to 20 Mb and also increase up to buffer size with given following configuration:
client_max_body_size 20m; client_body_buffer_size 128k;
If you receive an error as shown below , then you must know that client_max_body_size is low:
“Request Entity Too Large” (413)
– Nginx Cache Control for Static Files (Browser Cache Control Directives)
Browser caching is also import if you have like to save resources and want to save bandwidth. It is very easy to setup with Nginx. We have given below is very basic setup where we have done a simple thing is logging (access log and not found log)turned off and headers those are expire are set to for 360 days.
location ~* .(jpg|jpeg|gif|png|css|js|ico|xml)$ { access_log off; log_not_found off; expires 360d; }
Now if you wish for more complicated headers or some other expiration by file types then you must configure both separately.
– Nginx Pass PHP requests to PHP-FPM
Here you have taken default tpc/ip stack or you can directly use Unix socket connection. Now you have to setup PHP-FPM listen exactly same ip:port or unix socket (with Unix socket also socket permission have to be right). Default setup use ip:port (127.0.0.1:9000) you off course must change ports and ips what PHP-FPM listens. Here is the primary configuration with Unix socket and example commented out:
# Pass PHP scripts to PHP-FPM location ~* .php$ { fastcgi_index index.php; fastcgi_pass 127.0.0.1:9000; ##fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; }
It is possible to run Nginx on another server and PHP-FPM on another.
– Prevent (deny) Access to Hidden Files with Nginx
It’s very common that all server root or the other public directories have some hidden files, and these are point with dot (.) and those are not intended to site users commonly . Public directories can have file of version control and directories, such as .svn, some IDE properties files and .htaccess files. Following deny access and turn off logging for all hidden files .
location ~ /. { access_log off; log_not_found off; deny all; }
Tips and Tricks PHP-FPM Configuration
– Configuration files PHP-FPM
Normally, PHP-FPM configuration files are located on /etc/php/7.1/fpm/php-fpm.conf file and /etc/php/7.1/fpm/pool.d/ is path. It is excellent and normal start which all pool has configs move to /etc/php/7.1/fpm/pool.d/ directory. You have to add following line on your php-fpm.conf file:
;;;;;;;;;;;;;;;;;;;;; ; FPM Configuration ; ;;;;;;;;;;;;;;;;;;;;; ; All relative paths in this configuration file are relative to PHP's install ; prefix (/usr). This prefix can be dynamically changed by using the ; '-p' argument from the command line. ; Include one or more files. If glob(3) exists, it is used to include a bunch of ; files from a glob(3) pattern. This directive can be used everywhere in the ; file. ; Relative path can also be used. They will be prefixed by: ; - the global prefix if it's been set (-p argument) ; - /usr otherwise include=/etc/php/7.1/fpm/pool.d/*.conf
– Global Configuration Tweaks PHP-FPM
Set up emergency_restart_threshold, emergency_restart_interval and process_control_timeout. Default values for these options are totally off, but I think it’s better option to use these example given below :
emergency_restart_threshold 10 emergency_restart_interval 1m process_control_timeout 10s
What it mean is ? So if you watch 10 PHP-FPM child processes exit with SIGSEGV or SIGBUS within time of 1 minute then PHP-FPM will restart automatically. This configuration is also has time limit for 10 seconds for child processes and you have to wait for its reaction on signals from master.
– Pools Configuration PHP-FPM
With PHP-FPM it is possible to try with other pools that are different for other sites and allocate resources are very correct and even have different users and groups use it for each pool. Following is an example of configuration files structure for PHP-FPM pools for three various sites (or actually two different part of same site):
/etc/php/7.1/fpm/pool.d/solutionclub.conf /etc/php/7.1/fpm/pool.d/ask.conf
Then configure pools for each of file.
/etc/php/7.1/fpm/pool.d/solutionclub.conf :
[solutionclub] listen = 127.0.0.1:9000 user = solutionclub group = solutionclub request_slowlog_timeout = 5s slowlog = /var/log/php-fpm/slowlog-solutionclub.log listen.allowed_clients = 127.0.0.1 pm = dynamic pm.max_children = 5 pm.start_servers = 3 pm.min_spare_servers = 2 pm.max_spare_servers = 4 pm.max_requests = 200 listen.backlog = -1 pm.status_path = /status request_terminate_timeout = 120s rlimit_files = 131072 rlimit_core = unlimited catch_workers_output = yes env[HOSTNAME] = $HOSTNAME env[TMP] = /tmp env[TMPDIR] = /tmp env[TEMP] = /tmp
/etc/php/7.1/fpm/pool.d/ask.conf
[ask] listen = 127.0.0.1:9001 user = ask group = ask request_slowlog_timeout = 5s slowlog = /var/log/php-fpm/slowlog-ask.log listen.allowed_clients = 127.0.0.1 pm = dynamic pm.max_children = 4 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 pm.max_requests = 200 listen.backlog = -1 pm.status_path = /status request_terminate_timeout = 120s rlimit_files = 131072 rlimit_core = unlimited catch_workers_output = yes env[HOSTNAME] = $HOSTNAME env[TMP] = /tmp env[TMPDIR] = /tmp env[TEMP] = /tmp
server { listen 80; fastcgi_hide_header X-Powered-By; server_name solutionclub.in www.solutionclub.in; access_log off; error_log /var/log/nginx/solutionclub.in-error.log; root /var/www/vhosts/www.solutionclub.in; index index.php; location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { log_not_found off; access_log off; } location ~ .php$ { try_files $uri =404; fastcgi_split_path_info ^(.+.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_index index.php; include fastcgi_params; } location / { try_files $uri $uri/ /index.php?$args; } location ~* .(asf|asx|css|js|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|otf|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|t?gz|tif|tiff|ttf|wav|webm|wma|woff|wri|xla|xls|xlsx|xlt|xlw|zip)$ { expires 31536000s; access_log off; log_not_found off; add_header Pragma public; add_header Cache-Control "max-age=31536000, public"; } error_page 403 /404.html; error_page 404 /404.html; # Redirect non-https traffic to https if ($scheme != "http") { return 301 http://$host$request_uri; } # }
For next site..
server { listen 80; fastcgi_hide_header X-Powered-By; server_name ask.solutionclub.in; access_log off; error_log /var/log/nginx/ask.solutionclub.in-error.log; root /var/www/vhosts/ask.solutionclub.in; index index.php; location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { log_not_found off; access_log off; } location ~ .php$ { try_files $uri =404; fastcgi_split_path_info ^(.+.php)(/.+)$; fastcgi_pass 127.0.0.1:9001; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_index index.php; include fastcgi_params; } location / { try_files $uri $uri/ /index.php?$args; } location ~* .(asf|asx|css|js|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|otf|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|t?gz|tif|tiff|ttf|wav|webm|wma|woff|wri|xla|xls|xlsx|xlt|xlw|zip)$ { expires 31536000s; access_log off; log_not_found off; add_header Pragma public; add_header Cache-Control "max-age=31536000, public"; } error_page 403 /404.html; error_page 404 /404.html; # Redirect non-https traffic to https if ($scheme != "http") { return 301 http://$host$request_uri; } # }
Good Job!!!
Now You have time to restart all services.
root@solutionclub:~# php-fpm7.1 -t [09-Mar-2018 18:11:36] NOTICE: configuration file /etc/php/7.1/fpm/php-fpm.conf test is successful
root@solutionclub:~# systemctl restart nginx root@solutionclub:~# systemctl restart php7.0.service
It is fine to test that how many number of PHP-FPM processes a server can handle easily, first you can start with Nginx and PHP-FPM and make a try to load some PHP pages, then the remaining heaviest pages. Then note the memory usage per PHP-FPM process as example with Linux top or htop command. Let’s suppose that the server you have 512 Mb memory and 220 Mb is used for PHP-FPM, every process take 24 Mb RAM (some huge content management system with plugins can easily use 20-40 Mb / per PHP page request or even more). Then it is easy to calculate the server max_children value:
220 / 24 = 9.17
So good pm.max_children value is 9. This is based on just quick average and later this will be something else when you find longer time memory usage / per process. After testing it’s much simple to setup pm.start_servers value, pm.min_spare_servers value and pm.max_spare_servers value.
Final example configuration could be following:
pm.max_children = 9 pm.start_servers = 3 pm.min_spare_servers = 2 pm.max_spare_servers = 4 pm.max_requests = 200
Max request by default per process are unlimited , but it’s better to set some low value, like 200 and try to avoid some memory issues. This setup style could handle huge amount of requests, even if the numbers seem to be small.
For more Detail : PHP-FPM, PHP-FPM Config, Nginx