웹사이트 검색

Rocky/Alma/CentOS 9|8에 PHP OPcache 설치


OPcache는 미리 컴파일된 스크립트 바이트코드를 공유 메모리에 저장하여 PHP의 성능을 향상시키기 위해 만들어졌습니다. PHP 스크립트를 메모리에 캐시함으로써, PHP가 각 요청마다 스크립트를 로드하고 파싱할 필요를 없애줍니다. PHP로 구축된 웹사이트나 웹 애플리케이션을 호스팅할 때, OPcache를 사용하면 응답 속도와 전체 로딩 시간이 크게 개선됩니다.

PHP OPcache가 작동하는 방식은 다음과 같습니다:

  1. 스크립트 컴파일: OPcache는 요청된 스크립트를 바이트코드로 컴파일합니다.
  2. 바이트코드 캐싱: 한 번 컴파일되면, 바이트코드는 더 빠른 접근을 위해 공유 메모리에 저장됩니다.
  3. 후속 요청 실행: 동일한 스크립트에 대한 요청이 다음에 수신될 때, 캐시된 바이트코드를 사용하므로 컴파일 단계를 건너뛰어 더 빠르게 실행됩니다.

요약하자면, OPcache를 사용하면 PHP 스크립트 실행 속도가 빨라지고, CPU와 메모리 사용량이 감소하며, 더 많은 동시 요청을 처리할 수 있어 시스템 확장성이 향상됩니다.

그렇다면 Rocky Linux/AlmaLinux 및 CentOS Stream 9|8 Linux 시스템에서 PHP OPcache를 어떻게 설치하고 구성할 수 있을까요? 설치 방법을 따라해보세요.

REMI에서 PHP 버전으로 전환

우리는 PHP가 설치된 시스템에서만 OPcache를 활성화할 수 있습니다. 언급된 시스템들은 AppStream 저장소에서 여러 버전의 PHP를 배포합니다. 그러나 Opcache는 REMI 저장소에서 제공됩니다.

PHP가 설치되어 있는지 확인하려면 다음 명령어를 실행하세요:

$ 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

저희 시스템에서 확인한 결과 버전은 8.2입니다. 따라서 PHP 모듈을 재설정할 수 있습니다.

sudo dnf module reset php -y

다음으로 Remi의 RPM 저장소를 설치합니다:

  • 엔터프라이즈 리눅스 9 – (Rocky/Alma/CentOS 스트림 9)
sudo dnf -y install https://rpms.remirepo.net/enterprise/remi-release-9.rpm
  • 엔터프라이즈 리눅스 8 – (Rocky/Alma/CentOS 스트림 8)
sudo dnf -y install https://rpms.remirepo.net/enterprise/remi-release-8.rpm

설치 프로그램은 종속성으로 EPEL 저장소를 자동으로 설정합니다. REMI가 작동하는지 확인하려면 다음을 실행하세요:

$ 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

다음 명령어를 실행하면 모든 PHP 모듈을 확인할 수 있습니다:

 dnf module list php

여기 샘플 출력이 있습니다:

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

이제 REMI에서 특정 PHP 모듈을 활성화합니다. 이전 출력에서 설치된 PHP 버전은 8.2였으므로 php:remi-8.2 모듈을 활성화해야 합니다.

sudo dnf module install php:remi-8.2 -y

대부분의 경우, 설치된 PHP 버전을 업그레이드하며 패키지를 제거하지는 않습니다.

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

PHP OPcache 설치하기

REMI의 RPM 저장소가 구성되면 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

이 예제에서는 PHP 버전 8.2에 맞는 php82-php-opcache를 설치하고 있습니다. 설치된 PHP에 맞는 버전으로 변경하세요.

sudo dnf install php82-php-opcache

설치된 패키지에 대한 자세한 정보는 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
...

PHP OPcache 구성

find 명령어를 사용하여 OPcache 모듈 경로를 찾으세요.

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

모듈은 설치 시 자동으로 로드되어야 합니다.

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

설치 프로그램은 또한 /etc/php.d 안에 구성 템플릿을 생성하며, 이를 사용자화할 수 있습니다.

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

파일을 편집할 수 있도록 엽니다.

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

우리 서버에서는 좋은 성능을 제공하기 위해 다음과 같은 설정을 사용하고 있습니다:

; 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

구성하고 사용자 정의할 수 있는 모든 옵션 목록은 공식 OPcache 문서를 참조하세요.

OPcache가 작동하는지 테스트

웹서버와 php-fpm 서비스를 재시작하세요.

  • 엔진엑스 웹 서버
sudo systemctl restart php-fpm nginx
  • Apache httpd 웹 서버
sudo systemctl restart php-fpm httpd

OPcache 런타임 설정 목록은 아래 명령어를 실행하여 확인할 수 있습니다:

php -i | grep opcache

우리 시스템에서 OPcache가 작동하는지 테스트하기 위한 샘플 PHP 스크립트를 만드세요.

  • 엔진엑스 웹 서버
sudo vi /usr/share/nginx/html/opcache.php
  • Apache httpd 웹 서버
sudo vi /var/www/html/opcache.php

내용을 파일에 추가하세요.

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

파일을 저장하고 http://serverIP_or_fqdn/opcache.php에서 열세요

이는 PHP OPcache가 우리 시스템에서 정상적으로 작동하고 있음을 확인시켜 줍니다. 이 글이 도움이 되었길 바라며, 더 빠른 웹사이트 로딩 시간을 기원합니다!