Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save safdar-tp/b7d282f25c86d029853451acf2a98904 to your computer and use it in GitHub Desktop.
Save safdar-tp/b7d282f25c86d029853451acf2a98904 to your computer and use it in GitHub Desktop.
CentOS 7 - Apache 2.4 + MOD_PROXY_FCGI + PHP-FPM 5.5 + InstantClient Oracle.

CentOS 7 - Apache 2.4 + PHP-FPM 5.5 + InstantClient Oracle.


Montando uma VM para o desenvolvimento de aplicações em PHP, utilizado o CentOS 7

(EM DESENVOLVIMENTO)

Downloads

Downloads de ferramentas e bibliotecas necessárias para a instalação da VM

Realize o download do arquivo oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm.

Realize a instalação do WinSCP, VMware Player e crie uma VM com a ISO do CentOS 7.

Como pretendo simular um ambiente de produção. Minha VM foi criada com as seguintes configurações:

  • Memory 2 GB
  • Processors 4
  • HD 20GB
  • Network NAT

Durante o processo de instalação a VM pegou o IP (192.168.183.134), guarde o seu IP gerado para acesso via WinSCP/SSH.

Instalação

Utilizando a ferramenta WinSCP, realize a cópia do arquivo oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm, para a sua VM e jogue na pasta "/tmp".

Acesse o terminal da VM, pelo WinSCP use "Ctrl+P" que será aberto o terminal. Vamos começar a brincadeira.

Por se tratar de uma VM de desenvolvimento local, vou desabilitar o Firewall e Selinux, que vem instalado e configurado por default. Caso for utilizar esse exemplo para outros ambientes recomendo que deixe os 2(dois) em funcionamento.

systemctl stop firewalld
systemctl disable firewalld
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
reboot

Instalação dos RPMs e Repositórios necessários

yum install net-tools nano wget libaio perl
rpm -Uvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-1.noarch.rpm
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
rpm -ivh /tmp/oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
echo '/usr/lib/oracle/12.1/client64/lib/' > /etc/ld.so.conf.d/Oracle-InstantClient-12.1.conf
ldconfig
yum update
reboot

Para evitar surpresas, realizei mais um reboot para validar a atualização de kernel.

Instalação do Apache, PHP e libs.

yum --enablerepo=remi,remi-php55 install httpd php-fpm php-common php-pecl-apcu php-gd php-intl php-mbstring php-mssql php-mysql php-mysqlnd php-oci8 php-xmlrpc php-openssl php-pgsql php-soap php-opcache php-mcrypt php-pecl-pthreads

Iniciando o serviço do Apache, setando para que seja iniciado ao boot e verificando o status.

systemctl start httpd.service
systemctl enable httpd.service
systemctl status httpd.service -l

Removendo o Warning da falta de ServerName do Apache.

echo "ServerName localhost" >> /etc/httpd/conf.d/servername.conf

Iniciando o serviço do PHP-FPM, setando para que seja iniciado ao boot e verificando o status.

systemctl start php-fpm.service
systemctl enable php-fpm.service
systemctl status php-fpm.service -l

Criando o arquivo info.php para validar as configurações do PHP.

printf '<?php\n   phpinfo();' > /var/www/html/info.php

Criando um VirtualHost utilizando o mod_proxy_fcgi

nano /etc/httpd/conf.d/localhost.conf
<VirtualHost *:80>
    
    ServerName localhost
    
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1

    DocumentRoot /var/www/html
    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/localhost_error.log
    CustomLog /var/log/httpd/localhost_access.log combined
</VirtualHost>
systemctl restart httpd.service
systemctl status httpd.service -l

Para validar as configurações acesse via navegador os endereços:

Configuração Apache

O Apache 2.4 no CentOS, praticamente carrega todos os módulos na sua instalação. Como não vou utilizar todos os módulos vou desabilitar e deixar apenas o que preciso.

Todas as configurações foram baseadas no [CIS Apache HTTP Server 2.4 Benchmark] (http://und.edu/cio/it-security/policy/_files/docs/cis-apache-http-server-2-4-benchmark-v1-1-0.pdf)

nano /etc/httpd/conf.modules.d/00-base.conf
#
# This file loads most of the modules included with the Apache HTTP
# Server itself.
#

#LoadModule access_compat_module modules/mod_access_compat.so
#LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
#LoadModule allowmethods_module modules/mod_allowmethods.so
#LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authz_core_module modules/mod_authz_core.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
#LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
#LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule data_module modules/mod_data.so
#LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
#LoadModule dumpio_module modules/mod_dumpio.so
#LoadModule echo_module modules/mod_echo.so
#LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule filter_module modules/mod_filter.so
#LoadModule headers_module modules/mod_headers.so
#LoadModule include_module modules/mod_include.so
#LoadModule info_module modules/mod_info.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule mime_module modules/mod_mime.so
LoadModule negotiation_module modules/mod_negotiation.so
#LoadModule remoteip_module modules/mod_remoteip.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule status_module modules/mod_status.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule suexec_module modules/mod_suexec.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule userdir_module modules/mod_userdir.so
#LoadModule version_module modules/mod_version.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so

#LoadModule buffer_module modules/mod_buffer.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule heartbeat_module modules/mod_heartbeat.so
#LoadModule heartmonitor_module modules/mod_heartmonitor.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule dialup_module modules/mod_dialup.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
#LoadModule reflector_module modules/mod_reflector.so
#LoadModule request_module modules/mod_request.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule speling_module modules/mod_speling.so
nano /etc/httpd/conf.modules.d/00-dav.conf
#LoadModule dav_module modules/mod_dav.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
nano /etc/httpd/conf.modules.d/00-lua.conf
#LoadModule lua_module modules/mod_lua.so
nano /etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
LoadModule mpm_event_module modules/mod_mpm_event.so
nano /etc/httpd/conf.modules.d/00-proxy.conf
# This file configures all the proxy modules:
LoadModule proxy_module modules/mod_proxy.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
nano /etc/httpd/conf.modules.d/00-systemd.conf
# This file configures systemd module:
LoadModule systemd_module modules/mod_systemd.so
nano /etc/httpd/conf.modules.d/01-cgi.conf
# This configuration file loads a CGI module appropriate to the MPM
# which has been configured in 00-mpm.conf.  mod_cgid should be used
# with a threaded MPM; mod_cgi with the prefork MPM.

<IfModule mpm_worker_module>
   LoadModule cgid_module modules/mod_cgid.so
   ThreadsPerChild           25
   StartServers               3
   ServerLimit              400
   MinSpareThreads           75
   MaxSpareThreads          250
   MaxRequestWorkers      10000
   MaxConnectionsPerChild     0   
</IfModule>

<IfModule mpm_event_module>
   LoadModule cgid_module modules/mod_cgid.so
   ThreadsPerChild           25
   StartServers               3
   ServerLimit              400
   MinSpareThreads           75
   MaxSpareThreads          250
   MaxRequestWorkers      10000
   MaxConnectionsPerChild     0
</IfModule>

<IfModule mpm_prefork_module>
   LoadModule cgi_module modules/mod_cgi.so
   StartServers               5
   ServerLimit             1000
   MinSpareServers            5
   MaxSpareServers           10
   MaxRequestWorkers       1000
   MaxConnectionsPerChild     0
</IfModule>

Ufa!!! deu trabalho testar todos os módulos para saber o que precisa para rodar.

Com base no documento, vou criar um arquivo de segurança para aplicar as regras que não estão sendo aplicadas.

nano /etc/httpd/conf.d/security.conf
#
# http://und.edu/cio/it-security/policy/_files/docs/cis-apache-http-server-2-4-benchmark-v1-1-0.pdf
#

Timeout 10
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
LimitRequestline 512
LimitRequestFields 100
LimitRequestFieldsize 1024
LimitRequestBody 102400
systemctl restart httpd.service
Configuração PHP

nano /etc/php.ini

Altere as seguintes linhas:

date.timezone = "America/Sao_Paulo"
default_charset = "UTF-8"
systemctl restart php-fpm.service
Configuração InstantClient Oracle

Configurações das Variáveis de Ambiente.

nano /etc/sysconfig/php-fpm

Incluir no arquivo o NLS_LANG, conforme arquivo abaixo:

# Additional environment file for php-fpm

# This file is deprecated when systemd is used and
# will be removed in the future

# To alter the FPM environment, copy the unit file
# from /usr/lib/systemd/system/php-fpm.service
# to   /etc/systemd/system/php-fpm.service
# and add an Environment line

# With systemd >= 204 you can simply drop a file with the
# suffix .conf in /etc/systemd/system/php-fpm.service.d, with
#     [Service]
#     Environment=FOO=bar

# See systemd documentation.
#    man systemd.unit
#    man systemd.exec

NLS_LANG = 'BRAZILIAN PORTUGUESE_BRAZIL.AL32UTF8'
NLS_TERRITORY		= 'BRAZIL'
NLS_DUAL_CURRENCY	= 'R$'
NLS_CURRENCY		= 'R$'
NLS_ISO_CURRENCY	= 'BRAZIL'
NLS_DATE_LANGUAGE	= 'BRAZILIAN PORTUGUESE'
NLS_DATE_FORMAT		= 'DD/MM/YYYY'
NLS_TIME_FORMAT		= 'HH24:MI:SS'
NLS_TIMESTAMP_FORMAT 	= 'DD/MM/YYYY HH24:MI:SS'

Próximo passo é incluir as variáveis no pool do php-fpm

nano /etc/php-fpm.d/www.conf

Segue conteúdo e local aonde deve ser incluido.

...

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
env[HOSTNAME] = 'localhost'
env[NLS_LANG] = 'BRAZILIAN PORTUGUESE_BRAZIL.AL32UTF8'
env[NLS_TERRITORY] = 'BRAZIL'
env[NLS_DUAL_CURRENCY] = 'R$'
env[NLS_CURRENCY] = 'R$'
env[NLS_ISO_CURRENCY] = 'BRAZIL'
env[NLS_DATE_LANGUAGE] = 'BRAZILIAN PORTUGUESE'
env[NLS_DATE_FORMAT] = 'DD/MM/YYYY'
env[NLS_TIME_FORMAT] = 'HH24:MI:SS'
env[NLS_TIMESTAMP_FORMAT] = 'DD/MM/YYYY HH24:MI:SS'

...

As informações são redundantes, mas foi a unica forma que consegui para funcionar em ambientes (RHEL 7 e CentOS 7)

systemctl restart php-fpm.service
Configuração Apc Cache

nano /etc/php.d/apcu.ini
; Enable APCu extension module
extension = apcu.so

apc.enabled=1
apc.shm_segments=1

;32M per WordPress install
apc.shm_size=128M

;Relative to the number of cached files (you may need to watch your stats for a day or two to find out a good number)
apc.num_files_hint=7000

;Relative to the size of WordPress
apc.user_entries_hint=4096

;The number of seconds a cache entry is allowed to idle in a slot before APC dumps the cache
apc.ttl=7200
apc.user_ttl=7200
apc.gc_ttl=3600

;Setting this to 0 will give you the best performance, as APC will
;not have to check the IO for changes. However, you must clear
;the APC cache to recompile already cached files. If you are still
;developing, updating your site daily in WP-ADMIN, and running W3TC
;set this to 1
apc.stat=1

;This MUST be 0, WP can have errors otherwise!
apc.include_once_override=0

;Only set to 1 while debugging
apc.enable_cli=0

;Allow 2 seconds after a file is created before it is cached to prevent users from seeing half-written/weird pages
apc.file_update_protection=2

;Leave at 2M or lower. WordPress does't have any file sizes close to 2M
apc.max_file_size=2M

apc.cache_by_default=1
apc.use_request_time=1
apc.slam_defense=0
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.stat_ctime=0
apc.canonicalize=1
apc.write_lock=1
apc.report_autofilter=0
apc.rfc1867=0
apc.rfc1867_prefix =upload_
apc.rfc1867_name=APC_UPLOAD_PROGRESS
apc.rfc1867_freq=0
apc.rfc1867_ttl=3600
apc.lazy_classes=0
apc.lazy_functions=0
Configuração Zend OpCache

nano /etc/php.d/opcache.ini
; Enable Zend OPcache extension module
zend_extension=opcache.so

; 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.
opcache.memory_consumption=128

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

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 100000 are allowed.
opcache.max_accelerated_files=7000

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

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
;opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=60

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; If disabled, all PHPDoc comments are dropped from the code to reduce the
 ;size of the optimized code.
;opcache.save_comments=1

; If disabled, PHPDoc comments are not loaded from SHM, so "Doc Comments"
; may be always stored (save_comments=1), but not loaded by applications
; that don't need them anyway.
;opcache.load_comments=1

; If enabled, a fast shutdown sequence is used for the accelerated code
opcache.fast_shutdown=1

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

; A bitmask, where each bit enables or disables the appropriate OPcache
; passes
;opcache.optimization_level=0xffffffff

;opcache.inherited_hack=1
;opcache.dups_fix=0

; The location of the OPcache blacklist file (wildcards allowed).
; Each OPcache blacklist file is a text file that holds the names of files
; that should not be accelerated.
opcache.blacklist_filename=/etc/php.d/opcache*.blacklist

; Allows exclusion of large files from being cached. By default all files
; are cached.
;opcache.max_file_size=0

; Check the cache checksum each N requests.
; The default value of "0" means that the checks are disabled.
;opcache.consistency_checks=0

; How long to wait (in seconds) for a scheduled restart to begin if the cache
; is not being accessed.
;opcache.force_restart_timeout=180

; OPcache error_log file name. Empty string assumes "stderr".
;opcache.error_log=

; All OPcache errors go to the Web server log.
; By default, only fatal errors (level 0) or errors (level 1) are logged.
; You can also enable warnings (level 2), info messages (level 3) or
; debug messages (level 4).
;opcache.log_verbosity_level=1

; Preferred Shared Memory back-end. Leave empty and let the system decide.
;opcache.preferred_memory_model=

; Protect the shared memory from unexpected writing during script execution.
; Useful for internal debugging only.
;opcache.protect_memory=0
Ferramenta para tunning do apache

wget -O /sbin/check_httpd_limits https://check-httpd-limits.googlecode.com/svn/trunk/check_httpd_limits.pl
chmod +x /sbin/check_httpd_limits

Para checar as configurações do seu apache

check_httpd_limits --config=/etc/httpd/conf.modules.d/01-cgi.conf --verbose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment