This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

PHP-FPM Performance Tuning: A Detailed Guide to Optimizing Your Web Applications

Updated on November 7, 2023

8 Min Read
Php fpm

In the pursuit of speed and efficiency, our engineering team is constantly innovating and refining our technology stack. A key goal of these enhancements is to accelerate the overall processes within our platform.

In line with this commitment, we integrated PHP-FPM into all our servers as part of our ongoing efforts to boost performance and implement continuous improvements. This integration marks a significant step forward for applications hosted on Cloudways servers.

Now, these applications are expected to deliver performance that’s up to 3 times faster. This article will provide a detailed look at how this integration enhances PHP-FPM performance and optimizes your web applications.

What Is PHP-FPM and Why Use It?

PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites. It’s an efficient method to process dynamic content on your website, providing a significant speed boost.

It maintains pools (workers ready to serve PHP code) to accomplish this. These persistent PHP processes can serve queries instantly without any delay in initializing the PHP process. This speeds up your PHP environment and, eventually, your web applications.

Main Features of PHP-FPM

Let’s look at the features that make PHP-FPM a powerful tool for managing high-traffic websites.

  • Manages tasks by initiating and concluding them independently.
  • Adapts to various work settings, including ports, logging patterns, and file uploads.
  • Uses existing configuration files to complete requests and flush data.
  • Manages data from databases and high-traffic websites.
  • Enhances security measures and prevents server overloading.
  • Offers high configurability with different uid/gid/chroot/environment and php.ini settings.
  • Provides several options for performance tuning.

PHP-FPM vs. mod_PHP Performance

mod_PHP is a module for the Apache web server that allows PHP to be run as part of the basic suite of Apache. This means that when a user requests a PHP page, Apache includes mod_PHP, which interprets and processes the PHP code.

While both PHP-FPM and mod_PHP have their advantages, PHP-FPM is generally faster and more flexible. It doesn’t have to start an individual process for each request as mod_PHP does, making it more efficient for serving concurrent requests.

We tested a WordPress site on DigitalOcean’s 4GB server using both PHP-FPM and mod_PHP. We did not use Varnish or Turpentine for the test. Each time, we noticed increased performance and stability with the stack that contained PHP-FPM.

Performance with mod_PHP

The test generated 38,046 successful hits in 295.0 seconds with a data transfer of 7,399.11 KB in and 206,219.42 KB out from the app. The average hit rate of 128.0/second translates to about 1,1059,200 hits/day.

The average response time was 2150 ms.

wordpress-mod-php

Performance with PHP-FPM

The only thing different in this test is the addition of PHP-FPM.

The test generated 85,829 successful hits in 295.0 seconds with a transfer of 16,465.18 KB in and 465,728.74 KB of data out from the app. The average hit rate of 290.0/second translates to about 25,056,000 hits/day.

The average response time was 628 ms.

wordpress-php-fpm

Test generated 85,829 successful hits in 295.0 seconds with a transfer of 16,465.18 KB in and 465,728.74 KB of data out from the app. The average hit rate of 290.0/second translates to about 25,056,000 hits/day.

The average response time was 628 ms.

You might also like: PHP 5.6 Vs PHP 7 – Performance Benchmarks With Symfony 3

Results of Performance Benchmarks

You can notice that PHP-FPM made our test website almost 350% faster when it comes to loading times. Plus, it made the site twice as resource-efficient as it was with mod_php.

PHP-FPM, one of the newest ways to use PHP in conjunction with a web server, is an alternative PHP FastCGI implementation. This module of PHP can be used with any web server, which is compatible with the protocol of FastCGI.

PHP-FPM’s main benefit is its pool management system. Each PHP-FPM pool is like a separate PHP instance with its own settings, limits, and rules. This includes things like child processes, modules, environment variables, directories, and logs.

When to Use PHP-FPM or mod_PHP?

For high-traffic websites serving many concurrent users, PHP-FPM is likely the best choice. It’s designed for heavy loads and uses a pool management system to handle multiple PHP instances, ensuring optimal performance.

However, for smaller websites with less traffic and resources, like those in a shared hosting environment, mod_PHP could be sufficient. It’s an older PHP handler that runs as an Apache module, and it’s simpler to use and adequate for smaller sites.

Boost Your Web Applications with PHP-FPM on Cloudways

Switch to Cloudways today and propel your web applications forward with enhanced speed, security, and customization.

Enable PHP-FPM Manually on Docker

Let’s enable PHP-FPM on Docker for improved performance and efficient handling of your PHP applications.

Step 1: Creating a PHP App

Create a simple hello world PHP application by creating a file named hello.php.

<html>
    <head>
        <title>PHP Hello World!</title>
    </head>
    <body>
        <?php echo '<h1>Hello World</h1>'; ?>
        <?php phpinfo(); ?>
    </body>
</html>

Step 2: Creating a Dockerfile

Create a Dockerfile using the FPM variant of PHP (php:7.2-fpm in this case) and copy your PHP source code into a directory in the Docker image.

# docker build . -t my-php-app:1.0.0

FROM php:8.2-fpm
RUN mkdir /app
COPY hello.php /app

Step 3: Setting up Configmap

In Kubernetes, we’ll run two containers in a pod: one for PHP-FPM to handle PHP processing, and another for Nginx as a web server, both accessing a shared volume.

We’ll configure the Nginx container and direct it to send any *.php file requests to our PHP-FPM application via localhost:9000.

# First, create a ConfigMap whose contents are used
# as the nginx.conf file in the web server. 
# This server uses /var/www/html as its
# root document directory. When the server gets a 
# request for *.php, it will forward that request
# to our PHP-FPM container.

kind: ConfigMap
apiVersion: v1
metadata:
  name: nginx-config
data:
  nginx.conf: |
    events {
    }
    http {
      server {
        listen 80 default_server;
        listen [::]:80 default_server;
        
        # Set nginx to serve files from the shared volume!
        root /var/www/html;
        server_name _;
        location / {
          try_files $uri $uri/ =404;
        }
        location ~ \.php$ {
          include fastcgi_params;
          fastcgi_param REQUEST_METHOD $request_method;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          fastcgi_pass 127.0.0.1:9000;
        }
      }
    }

Step 4: Creating the Kubernetes Pod

Create a Kubernetes pod to run your application container and the Nginx web server sidecar, and make sure to review the comments in the gist.

# Create a pod containing the PHP-FPM application (my-php-app)
# and nginx, each mounting the `shared-files` volume to their
# respective /var/www/html directories.

kind: Pod
apiVersion: v1
metadata:
  name: phpfpm-nginx-example
spec:
  volumes:
    # Create the shared files volume to be used in both pods
    - name: shared-files
      emptyDir: {}
    
    # Add the ConfigMap we declared above as a volume for the pod
    - name: nginx-config-volume
      configMap:
        name: nginx-config

  containers:
    # Our PHP-FPM application
    - image: my-php-app:1.0.0
      name: app
      volumeMounts:
        - name: shared-files
          mountPath: /var/www/html
      # Important! After this container has started, the PHP files
      # in our Docker image aren't in the shared volume. We need to 
      # get them into the shared volume. If we tried to write directly
      # to this volume from our Docker image the files wouldn't appear
      # in the nginx container.
      #
      # So, after the container has started, copy the PHP files from this
      # container's local filesystem (/app -- added via the Docker image) 
      # to the shared volume, which is mounted at /var/www/html.
      lifecycle:
        postStart:
          exec:
            command: ["/bin/sh", "-c", "cp -r /app/. /var/www/html"]
    
    # Our nginx container, which uses the configuration declared above,
    # along with the files shared with the PHP-FPM app.
    - image: nginx:1.7.9
      name: nginx
      volumeMounts:
        - name: shared-files
          mountPath: /var/www/html
        - name: nginx-config-volume
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf

Change PHP-FPM Settings on Cloudways

For servers launched after August 23rd, 2016, on the Cloudways Platform, PHP-FPM is enabled by default, and mod_PHP is retired. For older servers, PHP-FPM can be activated by following this guide.

Step 1: Navigate to Application Settings

  • Log in to your Cloudways account;
  • From the top menu bar, open Servers;
  • Select the server where your application is installed.
  • Click the globe icon.
  • Choose your application.
  • Under Application Management, select Application Settings.
  • Navigate to PHP FPM Settings.

Step 2: Configure PHP-FPM Settings

Please use this editor carefully and enter values in the proper format. You may risk breaking your application(s) with incorrect settings.

The allowed directives are php_flag, php_admin_flag, php_value, and php_admin_value. Make sure there is no semicolon (;) before the rules you have added, or else it will act as a comment.

  • php_flag is used to set boolean values for options. Allowed values for directives are On or Off. For example, php_flag[log_errors] = on
  • php_value is used for everything else other than the boolean (On and Off) parameters. For example: php_value[error_log] /some/dir/to/log/php_errors.log
  • Use php_admin_flag and php_admin_value if you do not wish to use php.ini, .htaccess or PHP call ‘ini_set’ (in the code) to override PHP settings.

Examples of Common PHP Directives

You can use these PHP directives to control different aspects of a PHP script’s execution.

Edit the Post Max Size

In PHP, the post_max_size directive controls the maximum size of POST data that can be sent to a PHP script. You can edit this directive in your PHP configuration file (usually php.ini) to increase or decrease the maximum allowed size.

Increase the post_max_size to 100MB:

post_max_size = 100M

Increase the post_max_size to 1GB:

post_max_size = 1G

Remember to adjust this setting according to your server’s capabilities and requirements, as extremely large values can lead to excessive memory usage and potential security risks.

Set the Max Input Time

In PHP, the max_input_time directive determines the maximum amount of time in seconds that the PHP script is allowed to process input data.

If the script execution time exceeds this limit, PHP will terminate the script. You can edit the max_input_time directive in your PHP configuration file (usually php.ini) to set the desired value.

Set the max_input_time to 60 seconds:

max_input_time = 60

Set the Max Execution Time

The max time a PHP script can take to process data (regardless of the size) can be easily changed. In the following example, this time has been set to 120 seconds:

php_admin_value[max_execution_time] = 120

Set the Memory Limit

The maximum memory size that a PHP script can allocate can be easily set. In the following example, the maximum memory size is set to 96 MB:

php_admin_value[memory_limit] = 96M

Summary

Choosing between PHP-FPM and mod_PHP can greatly affect your web app’s performance. Our benchmarks show that PHP-FPM excels in speed and resource efficiency. Therefore, making an informed decision can significantly improve your overall performance.

To facilitate this, we’ve simplified the process of adjusting PHP-FPM settings via Cloudways. This allows for easy fine-tuning of your application’s performance. In addition, we’ve provided examples of PHP directives as a further means to optimize your PHP configuration.

Q: What is PHP-FPM used for?

A: PHP-FPM (FastCGI Process Manager) is a web tool used to speed up the performance of a website. It is much faster than traditional CGI based methods and has the ability to handle tremendous loads simultaneously.

Q: How to resolve “PHP-FPM service is not running” error?

A: To resolve this error, simply change the config file with /var/run/php5-fpm.pid in place of /var/run/php-fpm.pid. This could possibly solve the above stated error in minutes.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now