Properly restart Opcache after deployment

When you are deploying code to a server and not with containers then it is critical to know how to properly restart Opcache.

Why? Opcache never throws old files out of the cache. 

Therefore, if a new version is deployed in a completely new directory, all files from the old version will remain in the cache and clog it. The cache may be full with files from old versions and the new file version of the application would not be saved in the cache, leading to Opcache recompiling them over and over again at great cost to performance.

There are two possible solutions to this problem. The first and the simplest one, but also the one with a catch, is to restart the “php-fpm” process after the deployment of the new version. But then currently processed requests are aborted during the short time of the restart.

The second and more sustainable solution is to use gordalina/cachetool or an alternative such as chop. The documentation recommends this two steps to install the tool:

curl -sLO https://github.com/gordalina/cachetool/releases/latest/download/cachetool.phar
chmod +x cachetool.phar

And then run the following command on the CLI:

php cachetool.phar opcache:reset

Cachetool automatically detects PHP-FPM with this approach:

  1. Look for Unix sockets called “php*.sock” in /usr/run/ and /usr/run/php directories
  2. Assume PHP-FPM runs on 127.0.0.1:9000 

If your PHP-FPM uses unix sockets in a different directory, or runs on a different IP and port, then you can explicitly pass this with an argument:

php cachetool.phar opcache:reset --fcgi=/var/run/php/php8.2-fpm-profiler.sock

You only need to reset OPcache once, when you operate PHP-FPM with multiple separate pools, for example when separating slow backend and regular frontend traffic with pools as we have discussed on this blog before. This resets the cache across all pools.

What an AI would never be able to tell you the way we can! Follow us on LinkedIn or X and subscribe to our newsletter to take a deep dive into technical issues surrounding PHP performance.

You’ll never know until you try … our free trial!

Benjamin Benjamin 02.05.2024