Instalează PHP OPcache pe Rocky/Alma/CentOS 9|8


OPcache este conceput pentru a îmbunătăți performanța PHP prin stocarea codului byte precompilat al scripturilor în memoria partajată. Prin stocarea în cache a scripturilor PHP în memorie, se elimină necesitatea ca PHP să încarce și să analizeze scripturile la fiecare cerere primită. Atunci când găzduiți site-uri web sau aplicații web construite în PHP, utilizarea OPcache va îmbunătăți semnificativ timpul de răspuns și timpii generali de încărcare.

Așa funcționează PHP OPcache:

  1. Compilarea scriptului: OPcache compilează un script solicitat în cod byte.
  2. Cache-ul de bytecode: Odată compilat, bytecode-ul este stocat în memoria partajată pentru un acces mai rapid.
  3. Executarea cererilor ulterioare: Data viitoare când se primește o cerere pentru același script, se utilizează bytecode-ul din memorie cache, evitând astfel pasul de compilare și rezultând o execuție mai rapidă.

În rezumat, folosind OPcache vei experimenta un timp de execuție mai rapid al scripturilor PHP, un impact redus asupra procesorului și memoriei și o scalabilitate mai bună a sistemului, deoarece poate gestiona mai multe cereri simultane.

Cum poți instala și configura PHP OPcache pe sistemele Linux Rocky/AlmaLinux și CentOS Stream 9|8. Urmează pașii pentru ghidul complet.

Comută la ediția PHP de la REMI

Putem activa OPcache doar pe un sistem cu PHP instalat. Sistemele menționate distribuie mai multe versiuni de PHP în depozitele AppStream. Dar Opcache este furnizat în depozitele REMI.

Pentru a verifica dacă PHP este instalat, executați comanda:

$ 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

Din sistemul meu putem confirma că versiunea este 8.2. Așadar, putem reseta modulul PHP.

sudo dnf module reset php -y

Următorul pas este să instalăm repository-ul RPM al lui 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

Programul de instalare va configura automat depozitul EPEL ca o dependență. Pentru a valida că REMI funcționează, executați:

$ 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

Toate modulele PHP pot fi verificate rulând următoarea comandă:

 dnf module list php

Iată exemplul de rezultat:

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

Acum, activează modulul PHP specific de la REMI. Din rezultatul anterior, versiunea PHP instalată a fost 8.2, ceea ce înseamnă că ar trebui să activăm modulul php:remi-8.2.

sudo dnf module install php:remi-8.2 -y

În majoritatea cazurilor, va actualiza versiunea de PHP instalată și nu va dezinstala pachetele.

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

Instalarea PHP OPcache

Cu depozitul RPM al REMI configurat, putem căuta versiunile disponibile ale 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

În acest exemplu instalăm php82-php-opcache, care este specific versiunii PHP 8.2. Schimbați cu o versiune potrivită pentru PHP-ul pe care îl aveți instalat.

sudo dnf install php82-php-opcache

Mai multe informații despre pachetul instalat pot fi obținute folosind comenzile 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
...

Configurează PHP OPcache

Folosește comanda find pentru a localiza calea modulului OPcache.

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

Modulul ar trebui să se încarce automat după instalare.

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

Programul de instalare va crea, de asemenea, un șablon de configurare în interiorul /etc/php.d, pe care îl poți personaliza.

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

Deschide fișierul pentru editare.

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

Pe serverul nostru, folosim următoarele setări pentru a oferi o performanță bună:

; 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ți documentația oficială OPcache pentru o listă completă de opțiuni pe care le puteți configura și personaliza.

Test OPcache funcționează

Repornește serviciile webserver și php-fpm.

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

Listarea configurațiilor de rulare OPcache se poate face executând următoarele comenzi:

php -i | grep opcache

Creează un script PHP de probă pentru a testa dacă OPcache funcționează în sistemul nostru.

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

Adaugă conținutul în fișier.

<?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.";
}
?>

Salvați și deschideți fișierul de la http://serverIP_or_fqdn/opcache.php

Acest lucru confirmă că PHP OPcache funcționează bine în sistemul nostru. Sperăm că acest articol a fost util și vă dorim timpi mai rapizi de încărcare a site-ului!