Настройка PHP OPcache для оптимизация работы сайта
Zend OPcache — PHP-акселератор, обеспечивает ускорение выполнения PHP кода благодаря кэшированию и оптимизации, сохраняет скомпилированный байт-код в разделяемой памяти.
Opcache позволяет значительно ускорить скорость генерации страниц.
OPcache включен по умолчанию начиная с PHP 5.5
Создадим файл конфигурации OPcache:
echo > /etc/php.d/10-opcache.ini
и добавим в него конфиг (пример конфигурации)
Не стоит использовать готовые конфигурации найденные в интернете. Это может привести к остановке работы сайта. Подбирайте индивидуально.
zend_extension=opcache.so opcache.enable=1 opcache.memory_consumption=512 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=130987 opcache.max_wasted_percentage=5 opcache.use_cwd=1 opcache.validate_timestamps=1 opcache.revalidate_path=1 opcache.enable_file_override=1 opcache.fast_shutdown=1 opcache.save_comments=1 opcache.load_comments=1
После чего необходимо перезапустить веб сервер, в данном случае apache
Включить JIT в PHP 8
Компилятор JIT (Just In Time) в PHP 8 реализован как часть расширения Opcache и призван компилировать операционный код в инструкции процессора в реальном времени. Что позволяет еще больше повысить производительность.
Для включения необходимо указать размер буфера opcache.jit_buffer_size, по умолчанию 0.
Добовляем в наш файл /etc/php.d/10-opcache.ini строку:
opcache.jit_buffer_size=128M
и перезапускаем веб сервер, это все что требуется.
Опции OPcache
Опция | По молчанию | Описание |
opcache.enable | 1 | включение/выключение OPcache |
opcache.enable_cli | 0 | включение OPcache при вызове PHP из командной строки |
opcache.memory_consumption | 64 | размер используемой памяти (в мб.) для хранения прекомпилированного PHP-кода |
opcache.interned_strings_buffer | 4 | количество памяти для пула строк в мегабайтах |
opcache.max_accelerated_files | 2000 | максимальное количество ключей в хэш-таблице OPcache, допустимы значения между 200 и 1000000 |
opcache.max_wasted_percentage | 5 | максимальный процент замусоренной памяти для запланированного перезапуска |
opcache.use_cwd | 1 | при включении добавляет текущую рабочую директорию в ключ скрипта для предотвращения возникновения колизий между файлами с одинаковым именем |
opcache.validate_timestamps | 1 | возможность обнуления OPcache вручную или перезапуском веб-сервера для того, чтобы привести в актуальное состояние данных об изменениях в файлах |
opcache.revalidate_freq | 2 | через какой промежуток времени (в секундах) проверять изменения временных меток для поддержания данных в памяти в актуальном состоянии, где 1 — проверка с периодичностью раз в секунду, 0 — постоянная проверка. |
opcache.file_update_protection | 2 | предотвращает кэширование файлов, которые были изменены меньше, чем в указанное время (в секундах) |
opcache.revalidate_path | включение или отключение оптимизации поиска файлов в include_path | |
opcache.save_comments | 1 | если выключено, все комментарии PHPDoc будут удалены из кода с целью уменьшения размера оптимизированного кода. |
opcache.load_comments | 1 | если выключено, то комментарии PHPDoc не будут загружаться из общей памяти |
opcache.fast_shutdown | 0 | если включено, будет использоваться последовательность быстрых выключений для оптимизированного кода |
opcache.enable_file_override | 0 | при включении OPcache будет проверять наличие закэшированного файла при вызовах file_exists(), is_file() и is_readable() |
opcache.optimization_level | 0xffffffff | битовая маска, в которой каждый бит включает или отключает в соответствующие проходы OPcache |
opcache.inherited_hack | 1 | включение этого хака при ошибках вида can’t redeclare class |
opcache.dups_fix | 0 | Необходимо включить при появлении ошибок вида Can’t redeclare class |
opcache.blacklist_filename | месторасположение списка файлов, к которым запрещен доступ для OPcache | |
opcache.max_file_size | 0 | указывает максимальный размер файла для кеширования, позволяет исключать большие файлы |
opcache.consistency_checks | 0 | проверять контрольную сумму кэша каждое N-ое количество запросов, подсчет контрольной суммы снижает производительность |
opcache.force_restart_timeout | 180 | время ожидания (в секундах) перед перезагрузкой в случае недоступности кэша |
opcache.error_log | определение названия и местоположения лога ошибок OPcache | |
opcache.log_verbosity_level | 1 | все ошибки OPcache отправляет в лог-файл веб-сервера. По умолчанию логируются только критические ошибки (0) и обычные ошибки (1). |
- disable — Полностью отключён, не может быть включён во время выполнения.
- off — Отключено, но может быть включено во время выполнения.
- tracing — Используйте трассировку JIT. Включено по умолчанию и рекомендуется для большинства пользователей.
- function — Использование функции JIT.
Похожие записи:
How to speed up your Laravel application with PHP OPcache?
Using PHP OPcache is a great way to improve your overall performance. OPcache stores pre-compiled script bytecode in memory, which eliminates the need for PHP to load and parse scripts on every request.
In this tutorial, you will learn how to use the Laravel along with OPcache to speed up your website!
Enable PHP OPcache
There are a couple of ways of checking if you already have PHP OPcache enabled.
You could either add a PHP info file in your Laravel public folder with the following content:
And then visit the file via your browser. After that, use CTRL+F and search for OPcache.
Another way of checking if OPcache is enabled is to run the following command via your terminal:
The output that you would see the following result:
If you don’t have OPcache enabled, you can install it with the following command on Ubuntu:
sudo apt install php-opcache
Configure PHP OPcache
Once you have OPcache installed, you can adjust some of the default configuration settings to optimize the performance.
To make those changes, you need to edit your php.ini file. If you are not sure where exactly the php.ini file is located at, you can again use a PHP info file to check the location.
Using your favorite text editor, open the file:
nano /etc/php/7.4/fpm/conf.d/10-opcache.ini
Then at the bottom of the file add the following configuration:
opcache.memory_consumption=256 opcache.interned_strings_buffer=64 opcache.max_accelerated_files=32531 opcache.validate_timestamps=0 opcache.enable_cli=1
A quick rundown of the values:
- opcache.memory_consumption=256: This is the size of the memory storage used by OPcache. You can increase the opcache.memory_consumption=256 value in case that you have enough RAM on your server.
- opcache.interned_strings_buffer=64: The amount of memory alocated to storing interned strings. The value is in megabytes.
- opcache.max_accelerated_files=32531: The number of scripts in the OPcache hash table or, in other words, how many scripts can be cached in OPcache.
- opcache.validate_timestamps=0: With this directive, we specify that OPcache should not be cleared automatically, which means that we would need to do this manually.
- opcache.enable_cli=1: This enables the OPcache for the CLI version of PHP, which could be beneficial if you are using any artisan commands.
Once you make the change, you need to restart PHP FPM:
systemctl restart php7.4-fpm.service
Configure Laravel OPCache
In order to have some better management over the caching, we will use the Laravel OPcache package.
To use the package, you would need to have Larave 7 or newer. To install the package, just run the following command:
composer require appstract/laravel-opcache
One important thing that you need to keep in mind is that your APP_URL needs to be set correctly in your .env file so that it matches your domain.
Once you have the package installed, it provides you with some excellent PHP artisan commands which you could use to help you manage your OPcache:
— Artisan command to clear OPcache:
— Artisan command to show OPcache config:
php artisan opcache:config
— Artisan command to show OPcache status:
php artisan opcache:status
— Artisan command to pre-compile your application code:
php artisan opcache:compile
Enabling PHP OPcache is an excellent and quick way to boost the performance of your Laravel application without having to make any significant changes.
Zend OPCache — opcache.enable_cli 1 or 0? What does it do?
In the documentation it says «mostly used for debugging» which would lead me think «never enable it unless you’ve a problem and need to do some debugging,» however reading mostly everything that I could find about it says to enable it «opcache.enable_cli 1» but why? I could not find any information concerning this matter, so if anybody knows, why should I enable it if the documentation basically says to keep it on 0?
While the accepted answer stackoverflow.com/a/25047263/934195 is correct for PHP 5, there are answers which have relevant details for PHP 7 users like stackoverflow.com/a/35880017/934195
3 Answers 3
With PHP7 and file-based caching, it can now make sense to enable opcache for CLI. The best possibility would be to have a separate php.ini for CLI with the following configuration:
opcache.enable=1 opcache.enable_cli=1 opcache.file_cache="/tmp/php-file-cache" opcache.file_cache_only=1 opcache.file_cache_consistency_checks=1
opcache.file_cache_only=1 makes sure that the in-memory opcache is disabled and only files are used, which is what you want for CLI. This should boost execution time by quite a bit.
In the php.ini for FPM, you will want to have the same settings but use opcache.file_cache_only=0 , so in-memory opcache is used and the file cache is used as a fallback (which also makes FPM faster, because the file cache reduces warmup time when FPM is restarted or opcache is reset, because the cached files remain).
This way, CLI and FPM share the file cache, and FPM has the in-memory cache as a second primary cache for maximum speed. A great improvement in PHP7! Just make sure to choose a directory for opcache.file_cache that both CLI and FPM can write to, and that the same user does the writing/reading.
UPDATE 2017
I would not recommend to use the file cache with FPM anymore (only use it for CLI), because there is no way to reset the cache when setting opcache.validate_timestamps=0 — the file cache prevents PHP-FPM from recognizing any changes, because opcache_reset() or even a complete PHP-FPM restart does not affect the file cache and there is no equivalent for the file cache, so changed scripts are never noticed. I reported this as a «bug»/»feature request» in March 2016, but this is currently not seen as an issue. Just beware if you use opcache.validate_timestamps=0 !