Búsqueda de sitios web

Instalar PHP OPcache en Rocky/Alma/CentOS 9|8


El OPcache está diseñado para mejorar el rendimiento de PHP almacenando el bytecode de los scripts precompilados en memoria compartida. Al almacenar en caché los scripts PHP en memoria, se elimina la necesidad de que PHP cargue y analice los scripts en cada solicitud que recibe. Al alojar sitios web o aplicaciones web construidas en PHP, utilizar OPcache mejorará significativamente la capacidad de respuesta y los tiempos de carga en general.

Así es como funciona PHP OPcache:

  1. Compilación de scripts: OPcache compila un script solicitado en bytecode.
  2. Caché de bytecode: Una vez compilado, el bytecode se almacena en la memoria compartida para un acceso más rápido.
  3. Ejecución de solicitudes subsiguientes: La próxima vez que se reciba una solicitud para el mismo script, se utilizará el bytecode en caché, evitando así el paso de compilación y resultando en una ejecución más rápida.

En resumen, al usar OPcache experimentarás un tiempo de ejecución más rápido de los scripts PHP, una menor carga en la CPU y la memoria, y una mejor escalabilidad del sistema ya que puede manejar más solicitudes concurrentes.

Entonces, ¿cómo puedes instalar y configurar PHP OPcache en sistemas Linux Rocky Linux/AlmaLinux y CentOS Stream 9|8? Sigue leyendo para ver el paso a paso.

Cambiar a la edición PHP de REMI

Solo podemos habilitar OPcache en un sistema con PHP instalado. Los sistemas mencionados distribuyen múltiples versiones de PHP en los repositorios de AppStream. Pero Opcache se proporciona en los repositorios REMI.

Para verificar si PHP está instalado, ejecute el comando:

$ php --version
PHP 8.2.13 (cli) (built: Nov 21 2023 09:55:59) (NTS gcc x86_64)
Copyright (c) The PHP Group
Zend Engine v4.2.13, Copyright (c) Zend Technologies

Desde mi sistema podemos confirmar que la versión es 8.2. Por lo tanto, podemos reiniciar el módulo PHP.

sudo dnf module reset php -y

A continuación, instalamos el repositorio RPM de Remi:

  • Enterprise Linux 9 – (Rocky/Alma/CentoS Stream 9)
sudo dnf -y install https://rpms.remirepo.net/enterprise/remi-release-9.rpm
  • Enterprise Linux 8 – (Rocky/Alma/CentoS Stream 8)
sudo dnf -y install https://rpms.remirepo.net/enterprise/remi-release-8.rpm

El instalador configurará automáticamente el repositorio EPEL como dependencia. Para validar que REMI está funcionando, ejecute:

$ sudo dnf -y repolist
repo id                                                                                 repo name
appstream                                                                               Rocky Linux 8 - AppStream
baseos                                                                                  Rocky Linux 8 - BaseOS
epel                                                                                    Extra Packages for Enterprise Linux 8 - x86_64
extras                                                                                  Rocky Linux 8 - Extras
remi-modular                                                                            Remi's Modular repository for Enterprise Linux 8 - x86_64
remi-safe                                                                               Safe Remi's RPM repository for Enterprise Linux 8 - x86_64

Todos los módulos de PHP se pueden verificar ejecutando el siguiente comando:

 dnf module list php

Aquí está el ejemplo de salida:

Rocky Linux 8 - AppStream
Name                                        Stream                                              Profiles                                                          Summary
php                                         7.2 [d][x]                                          common [d], devel, minimal                                        PHP scripting language
php                                         7.3 [x]                                             common [d], devel, minimal                                        PHP scripting language
php                                         7.4 [x]                                             common [d], devel, minimal                                        PHP scripting language
php                                         8.0 [x]                                             common [d], devel, minimal                                        PHP scripting language
php                                         8.2 [x]                                             common [d], devel, minimal                                        PHP scripting language

Remi's Modular repository for Enterprise Linux 8 - x86_64
Name                                        Stream                                              Profiles                                                          Summary
php                                         remi-7.2 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-7.3 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-7.4 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-8.0 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-8.1 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-8.2 [x]                                        common [d], devel, minimal                                        PHP scripting language
php                                         remi-8.3 [x]                                        common [d], devel, minimal                                        PHP scripting language

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled

Ahora, activa el módulo PHP específico de REMI. Según la salida anterior, la versión de PHP instalada fue 8.2, esto significa que debemos activar el módulo php:remi-8.2.

sudo dnf module install php:remi-8.2 -y

En la mayoría de los casos, actualizará la versión de PHP que tienes instalada y no desinstalará los paquetes.

Dependencies resolved.
==============================================================================================================================================================================================================================
 Package                                               Architecture                                   Version                                                      Repository                                            Size
==============================================================================================================================================================================================================================
Upgrading:
 php-cli                                               x86_64                                         8.2.21-1.el8.remi                                            remi-modular                                         5.5 M
 php-common                                            x86_64                                         8.2.21-1.el8.remi                                            remi-modular                                         1.3 M
 php-fpm                                               x86_64                                         8.2.21-1.el8.remi                                            remi-modular                                         1.9 M
 php-mbstring                                          x86_64                                         8.2.21-1.el8.remi                                            remi-modular                                         583 k
 php-xml                                               x86_64                                         8.2.21-1.el8.remi                                            remi-modular                                         264 k
Installing dependencies:
 oniguruma5php                                         x86_64                                         6.9.9-1.el8.remi                                             remi-safe                                            213 k
Installing module profiles:
 php/common
Enabling module streams:
 php                                                                                                  remi-8.2

Transaction Summary
==============================================================================================================================================================================================================================
Install  1 Package
Upgrade  5 Packages

Total download size: 9.7 M
Is this ok [y/N]: y

Instalando PHP OPcache

Con el repositorio RPM de REMI configurado, podemos buscar las versiones disponibles de OPcache.

$ sudo dnf search opcache
Last metadata expiration check: 0:07:55 ago on Sun 28 Jul 2024 10:12:13 PM UTC.
============================================================================================== Name & Summary Matched: opcache ===============================================================================================
php-opcache.x86_64 : The Zend OPcache
php56-php-opcache.x86_64 : The Zend OPcache
php70-php-opcache.x86_64 : The Zend OPcache
php71-php-opcache.x86_64 : The Zend OPcache
php72-php-opcache.x86_64 : The Zend OPcache
php73-php-opcache.x86_64 : The Zend OPcache
php74-php-opcache.x86_64 : The Zend OPcache
php80-php-opcache.x86_64 : The Zend OPcache
php81-php-opcache.x86_64 : The Zend OPcache
php82-php-opcache.x86_64 : The Zend OPcache
php83-php-opcache.x86_64 : The Zend OPcache
php84-php-opcache.x86_64 : The Zend OPcache

En este ejemplo estamos instalando php82-php-opcache, que es específico para la versión de PHP 8.2. Cambia a una versión adecuada para tu PHP instalado.

sudo dnf install php82-php-opcache

Se puede consultar más información sobre el paquete instalado usando los comandos rpm -qi:

$ rpm -qi php82-php-opcache
Name        : php82-php-opcache
Version     : 8.2.21
Release     : 1.el8.remi
Architecture: x86_64
Install Date: Sun 28 Jul 2024 10:21:52 PM UTC
Group       : Unspecified
Size        : 1024035
License     : PHP-3.01
Signature   : RSA/SHA256, Tue 02 Jul 2024 02:07:23 PM UTC, Key ID 555097595f11735a
Source RPM  : php82-php-8.2.21-1.el8.remi.src.rpm
Build Date  : Tue 02 Jul 2024 01:33:41 PM UTC
Build Host  : builder.remirepo.net
Relocations : (not relocatable)
Packager    : Remi Collet
Vendor      : Remi's RPM repository <https://rpms.remirepo.net/> #StandWithUkraine
URL         : http://www.php.net/
Bug URL     : https://forum.remirepo.net/
Summary     : The Zend OPcache
...

Configurar PHP OPcache

Usa el comando find para localizar la ruta del módulo OPcache.

$ sudo find / -name opcache.so
/usr/lib64/php/modules/opcache.so
/usr/lib64/php-zts/modules/opcache.so

El módulo debería cargarse automáticamente al instalarlo.

$ php -m  | grep -i opcache
Zend OPcache
Zend OPcache

El instalador también creará una plantilla de configuración dentro de /etc/php.d, que puedes personalizar.

$ ls /etc/php.d/|grep opcache
10-opcache.ini
opcache-default.blacklist

Abre el archivo para editarlo.

sudo vi /etc/php.d/10-opcache.ini

En nuestro servidor, estamos utilizando la siguiente configuración para ofrecer un buen rendimiento:

; Enable Zend OPcache extension module
zend_extension=opcache

; Determines if Zend OPCache is enabled
opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1

; The OPcache shared memory storage size (in MB)
opcache.memory_consumption=512

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=128

; The maximum number of keys (scripts) in the OPcache hash table.
opcache.max_accelerated_files=10000

; The maximum percentage of "wasted" memory until a restart is scheduled.
opcache.max_wasted_percentage=5

; Enable timestamp validation, ensuring that cached files are up to date.
opcache.validate_timestamps=1

; Checks for script changes every 2 seconds.
opcache.revalidate_freq=2

; Path where OPcache can store file cache.
opcache.file_cache=/tmp

; Enables or disables opcode caching in shared memory.
opcache.file_cache_only=0

; Enables or disables checksum validation when script loaded from file cache.
opcache.file_cache_consistency_checks=1

; Other performance settings
opcache.fast_shutdown=1
opcache.enable_file_override=1
opcache.optimization_level=0x7FFFBFFF

Consulta la documentación oficial de OPcache para obtener una lista completa de opciones que puedes configurar y personalizar.

Probar si OPcache está funcionando

Reinicia los servicios de tu servidor web y php-fpm.

  • Servidor web Nginx
sudo systemctl restart php-fpm nginx
  • Servidor web Apache httpd
sudo systemctl restart php-fpm httpd

La lista de configuraciones de tiempo de ejecución de OPcache se puede obtener ejecutando los siguientes comandos:

php -i | grep opcache

Crea un script de PHP de ejemplo para probar si OPcache está funcionando en nuestro sistema.

  • Servidor web Nginx
sudo vi /usr/share/nginx/html/opcache.php
  • Servidor web Apache httpd
sudo vi /var/www/html/opcache.php

Agrega el contenido al archivo.

<?php
if (function_exists('opcache_get_status')) {
    $status = opcache_get_status();
    if ($status) {
        echo "OPcache is enabled on the server.";
    } else {
        echo "OPcache is disabled on the server..";
    }
} else {
    echo "OPcache is not installed.";
}
?>

Guarda y abre el archivo desde http://serverIP_or_fqdn/opcache.php

Esto confirma que PHP OPcache funciona correctamente en nuestro sistema. ¡Esperamos que este artículo haya sido útil y le deseamos tiempos de carga de sitios web más rápidos!