Blog Escola Linux

  

Como obter alta performance com Servidores Web Nginx e Apache

Como obter alta performance com Servidores Web Nginx e Apache

O Apache

O APACHE (HTTP Server) é o Web Server mais utilizado no mundo, além de ser compatível com várias aplicações, disponibilidade de muitos recursos, deste virtual host a Load Balancer. Os principais recursos são: Proxy reverso, virtual host, autenticação e Load Balancer.

Além do processo de instalação, tem que ser pensado e realizado um pôs instalação, os valores pré configurado não são adequados dependendo do objetivo da finalidade do servidor, para ambiente com grande volumetria de acesso, tem que ser realizado ajustes, o arquivo de configuração global e principal para realizar tal alteração, é o httpd.conf, dentre várias diretivas que podemos alterar.

O Nginx

O NGINX é um dos Web Server mais utilizado no mundo, além de ser compatível com várias aplicações, disponibiliza de muitos recursos, deste virtual host a Upstream. As principais funções são: proxy reverso, virtual host, servidor de cache e Upstream, o principal arquivo de configuração é o nginx.conf.

Estes testes foram efetuados em uma VPS da Hostinger.

Trabalhando com o Apache

# vi httpd.conf

# KEEPALIVE

KeepAlive on

MaxKeepAliveRequests 100

KeepAliveTimeout 15

#PARA 2 PROCESSADORES

#StartServers - QUANTIDADE INICIAL DE PROCESSOS

#MinSpareServers - MINIMO DE SERVIDORES CARREGADOS NO START

#MaxSpareServers - MAXIMO DE SERVIDORES CARREGADOS NO START

#MaxClients - MAXIMO DE CONEXOES ACEITAS

#ServerLimit - COMECA A FICAR LENTO E ENFILEIRANDO NOVAS CONEXOES

# TRABALHAR COM A IMPLANTACAO DE MULTI PROCESSOS 

StartServers 8

MinSpareServers 5

MaxSpareServers 10

ServerLimit 200

MaxClients 200

MaxRequestsPerChild 2000 

# TRABALHAR COM IMPLEMENTACAO MISTA DE PROCESSOS E THREADS 

StartServers 4

MaxClients 200

MinSpareThreads 20

MaxSpareThreads 25

ThreadsPerChild 25

MaxRequestsPerChild 0 

# DIRETORIO DE INFORMACOES E ESTATISTICAS DO SERVIDOR/APACHE 

SetHandler server-status

Order Deny,Allow

Deny from All

Allow from 127.0.0.1 

SetHandler server-info

Order Deny,Allow

Deny from All

Allow from 127.0.0.1 

Para setup de um virtual host, temos como exemplo uma configuração de exemplo e comentada.

# Listen IP/DNS:Porta

Listen www.site.com.br:80 

# URL

ServerName www.site.com.br:80

ServerAlias www.site.com.br site.com.br:80 192.168.249.167

ServerAdmin alexbmw00@gmail.com

# ROOT FOLDER

DocumentRoot /var/www/site

# INDEX

DirectoryIndex info.php index.html

# LOGS

ErrorLog /var/log/httpd/www.site.com.br-error.log

CustomLog /var/log/httpd/www.site.com.br-access.log common

# ACL APACHE 2.4/ 

#

Require all denied

Require ip 192.168.249.1

Require ip 192.168.249.167

Require ip 127.0.0.1

#Require not ip 192.168.249.1

# 

# SERVER STATUS

 SetHandler server-status

# AUTENTICATION

AuthType Basic

AuthName "Server Status"

AuthBasicProvider file

AuthUserFile "/etc/httpd/htpasswd"

Require valid-user

Para virtual proxy, temos o exemplo a seguir, a configuração está aplicada a suportar SSL (Secure Sock Layer).

# SSL DEFINICOES

SSLPassPhraseDialog builtin

SSLSessionCache shmcb:/var/cache/mod_ssl/scache(512000)

SSLSessionCacheTimeout 300

SSLRandomSeed startup file:/dev/urandom 256

SSLRandomSeed connect builtin

SSLCryptoDevice builtin

Para redirecionamento de endereços, utilizamos o motor de regras Rewrite.

# RETURN

Listen www.proxy.com.br:80

 

ServerName www.proxy.com.br:80

ServerAlias www.proxy.com.br proxy.com.br 192.168.249.167

ServerAdmin alexbmw00@gmail.com

RewriteEngine On

#RewriteCond %{HTTPS} Off

RewriteRule ^/?(.*) https://www.proxy.com.br [R]

#RewriteRule ^/?(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,P] 

Para o virtual proxy em si, temos a configuração:

# HTTPS

Listen www.proxy.com.br:445 https

ProxyVia On 

# URL

ServerName www.proxy.com.br:443

ServerAlias www.proxy.com.br proxy.com.br 192.168.249.167

ServerAdmin alexbmw00@gmail.com

# LOGS

ErrorLog /var/log/httpd/vproxy1.linuxcorp.br-error.log

CustomLog /var/log/httpd/vproxy1.linuxcorp.br-access.log common

# SSL

SSLProxyEngine On

SSLEngine On

SSLProtocol All -SSLv2

SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

# SSL CERTIFIED

SSLCertificateFile /etc/pki/tls/certs/localhost.crt

SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

# SSH PRESERVE

ProxyPreserveHost On

ProxyRequests Off

# SSH NO CHECK

SSLProxyVerify None

SSLProxyCheckPeerCN Off

SSLProxyCheckPeerName Off

SSLProxyCheckPeerExpire Off

# ACL 2.4* 

#

Require all denied

Require ip 192.168.249.1

Require ip 192.168.249.168

Require ip 127.0.0.1

#Require not ip 192.168.249.1

# 

Aqui é onde será feito o repasse para os servidores de backends juntamente com o complemento da URL.

# PROXY PASS /

ProxyPass / https://192.168.249.168/ connectiontimeout=5 timeout=30 max=50 retry=120 acquire=1000 KeepAlive=On

ProxyPassReverse /s http:/192.168.249.168/

Redirect Permanent / http://192.168.249.168/

ProxyPass /nagios https://192.168.249.168/nagios connectiontimeout=5 timeout=30 max=50 retry=120 acquire=1000 KeepAlive=On

ProxyPassReverse /nagios http:/192.168.249.168/nagios

Redirect Permanent /nagios http://192.168.249.168/nagios

ProxyPass /pnp4nagios https://192.168.249.168/pnp4nagios connectiontimeout=5 timeout=30 max=50 retry=120 acquire=1000 KeepAlive=On

ProxyPassReverse /pnp4nagios https:/192.168.249.168/pnp4nagios

Redirect Permanent /pnp4nagios https://192.168.249.168/pnp4nagios

ProxyPass /mrtg https://192.168.249.168/mrtg connectiontimeout=5 timeout=30 max=50 retry=120 acquire=1000 KeepAlive=On

ProxyPassReverse /mrtg https:/192.168.249.168/mrtg

Redirect Permanent /mrtg https://192.168.249.168/mrtg

ACLs na arvore maior do apache, no caso o /.

# ACL / 

#

Require all denied

Require ip 192.168.249.1

Require ip 192.168.249.167

Require ip 192.168.249.168

Require ip 127.0.0.1

#Require not ip 192.168.249.1

# 

Exemplo de balanceamento de carga com apache.

# HTTPS

Listen www.loadbalancer.com.br:443 https

ProxyVia On 

# URL

ServerName www.loadbalancer.com.br:443

ServerAlias www.loadbalancer.com.br loadbalancer.com.br 192.168.249.167

ServerAdmin alexbmw00@gmail.com

# LOGS

ErrorLog /var/log/httpd/www.loadbalancer.com.br-error.log

CustomLog /var/log/httpd/www.loadbalancer.com.br-access.log common

# SSL PROXY

SSLProxyEngine On

SSLEngine On

SSLProtocol All -SSLv2

SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

# SSL CERTIFIED

SSLCertificateFile /etc/pki/tls/certs/localhost.crt

SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

# PROXY PRESERV

ProxyPreserveHost On

ProxyRequests Off

# PROXY STATUS

ProxyStatus On

# NAO REPASSAR, UTILIZE !

ProxyPass /balancer-manager !

ProxyPass /server-status !

ProxyPass /server-info !

ProxyPass /status !

ProxyPass / balancer://mycluster/ nofailover=Off

# CLUSTER NAME 'mycluster'

ProxyPassReverse / balancer://mycluster

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED

# REPASSE/FORWARD 

# BACKENDS NGINX

BalancerMember http://192.168.249.200:1120 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.201:1121 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.202:1122 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.203:1123 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

# BACKENDS APACHE

BalancerMember http://192.168.249.200:1100 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.201:1101 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.202:1102 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

BalancerMember http://192.168.249.203:1103 connectiontimeout=5 timeout=30 max=50 retry=120 loadfactor=1 acquire=1000 KeepAlive=On

# TYPE BALANCER

#ProxySet lbmethod=bytraffic stickysession=ROUTEID

ProxySet lbmethod=byrequests stickysession=ROUTEID

#ProxySet lbmethod=bybusyness stickysession=ROUTEID

ProxySet timeout=120 

# ACL / 

#

Require all denied

Require ip 192.168.249.1

Require ip 192.168.249.167

Require ip 127.0.0.1

#Require not ip 192.168.249.1

# 

Acesso ao balancer manager via interface web.

# BALANCER MANAGER 

SetHandler balancer-manager

# AUTENTICATION

AuthName "Balancer Manager"

AuthType Basic

AuthBasicProvider file

AuthUserFile "/etc/httpd/htpasswd"

Require valid-user 

Visualizar as estatísticas do balancer e proxy.

# PROXY STATUS 

SetHandler server-status

# AUTENTICATION

AuthType Basic

AuthName "Proxy Status"

AuthBasicProvider file

AuthUserFile "/etc/httpd/htpasswd"

Require valid-user 

# SERVER STATUS 

SetHandler server-status

# AUTENTICATION

AuthType Basic

AuthName "Server Status"

AuthBasicProvider file

AuthUserFile "/etc/httpd/htpasswd"

Require valid-user 

Visualizar as informações de compilação, versão, etc do apache.

# SERVER INFO 

SetHandler server-info

# AUTENTICATION

AuthType Basic

AuthName "Server Info"

AuthBasicProvider file

AuthUserFile "/etc/httpd/htpasswd"

Require valid-user 

Módulos de compresso de dados.

# MOD DEFALTE 

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/x-javascript application/xml application/xhtml+xml "application/x-javascript \n\n" "text/html \n\n"

DeflateCompressionLevel 9 

Trabalhando com o Nginx

#vi nginx.conf

# USUARIO

user nginx;

# PROCESSADORES

worker_processes 8;

# LIMITE DE CONEXOES

events {

worker_connections 1000;

}

http {

sendfile on;

tcp_nopush on;

tcp_nodelay on;

keepalive_timeout 65;

types_hash_max_size 2048;

server_tokens off;

# PROTECAO DDoS

server_names_hash_bucket_size 64;

server_name_in_redirect off;

default_type application/octet-stream;

gzip on;

gzip_disable "msie6";

gzip_vary on;

gzip_proxied any;

gzip_comp_level 6;

gzip_buffers 16 8k;

gzip_http_version 1.1;

gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

# LIMITE POR IP

limit_conn_zone $binary_remote_addr zone=addr:100m;

limit_conn addr 100;

limit_conn_zone $binary_remote_addr zone=perip:100m;

limit_conn_zone $server_name zone=perserver:100m;

limit_req_zone $binary_remote_addr zone=one:100m rate=1r/s;

Exemplo de virtualhost, redirecionamento de URLs:

# REDIRECT

server {

listen 80;

server_name www.site.com.br::80;

return 302 https://$host$request_uri;>

}

# SITE

server {

ssl on;

listen www.site.linuxcorp.br:443 ssl ;

server_name www.site.linuxcorp.br site.linuxcorp.br 192.168.249.167;

index index.html

# WEB FOLDER

#autoindex on;

root /var/www/www.site.com.br/site;

# SITE FOLDER

# MAX FILE

client_max_body_size 1024M;

# LOGS

access_log /var/log/nginx/site-access.log;

error_log /var/log/nginx/site-error.log;

# CERTIFIED

ssl_certificate /etc/nginx/ssl/ca.crt;

ssl_certificate_key /etc/nginx/ssl/ca.key;

# TIMEOUT

ssl_session_timeout 5m;

keepalive_timeout 65;

tcp_nodelay on;

sendfile on;

# SSL VERSION

ssl_protocols SSLv3 TLSv1;

ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;

ssl_prefer_server_ciphers on;

# PATH WEB

location / {

try_files $uri $uri/ /index.html;

# ACL

allow 127.0.0.1;

allow 192.168.249.0/24;

deny all;

# IP LIMIT

limit_conn perip 50;

limit_conn perserver 50;

limit_req zone=one burst=50 nodelay;

}

# STATUS

location /nginx_status {

stub_status on;

access_log off;

# AUTENTICATION

auth_basic "NGINX STATUS";

auth_basic_user_file /etc/nginx/htpasswd;

}

}

Exemplo de virtual proxy:

# SITE

server {

ssl on;

listen www.proxy.com.br:443 ssl;

server_name www.proxy.com.br proxy.com.br 192.168.249.167;

# LOGS

access_log /var/log/nginx/proxy-access.log;

error_log /var/log/nginx/proxy-error.log;

# CERTIFIED

ssl_certificate /etc/nginx/ssl/ca.crt;

ssl_certificate_key /etc/nginx/ssl/ca.key;

# TIMEOUT

ssl_session_timeout 5m;

keepalive_timeout 120;

tcp_nodelay on;

sendfile on;

# SSL VERSION

ssl_protocols SSLv3 TLSv1;

ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;

ssl_prefer_server_ciphers on;

# PATH WEB FOR PASS

location / {

# PASS FOR URL

proxy_pass https://192.168.249.168/;

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# MAX BODY

client_max_body_size 100M;

client_body_buffer_size 128k;

# TIMEOUT

proxy_connect_timeout 120;

proxy_send_timeout 120;

proxy_read_timeout 120;

proxy_buffers 32 4k;

# IP LIMIT

limit_conn perip 50;

limit_conn perserver 50;

}

# ERROR PAGE

error_page 404 /404.html;

root /usr/share/nginx/html;

error_page 500 502 503 504 /50x.html;

location = /50x.html {

}

}

Exemplo de upstream.

# UPSTREAM SERVER MEMBERS

upstream www.upstream.com.br {

# REQUISITION

least_conn;

# PERSISTENT

#ip_hash;

# BACKENDS APACHE

server 192.168.249.200:1100 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.201:1101 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.202:1102 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.203:1103 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.204:1104 weight=1 max_fails=3 fail_timeout=15s;

# BACKENDS NGINX

server 192.168.249.200:1120 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.201:1121 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.202:1122 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.203:1123 weight=1 max_fails=3 fail_timeout=15s;

server 192.168.249.204:1124 weight=1 max_fails=3 fail_timeout=15s;

}

# SITE

server {

ssl on;

listen www.upstream.com.br:443 ssl;

server_name www.upstream.com.br: upstream.com.br:443 192.168.249.167;

# LOGS

access_log /var/log/nginx/upstream-access.log;

error_log /var/log/nginx/upstream-error.log;

# CERTIFIED

ssl_certificate /etc/nginx/ssl/ca.crt;

ssl_certificate_key /etc/nginx/ssl/ca.key;

# TIMEOUT

ssl_session_timeout 5m;

keepalive_timeout 120;

tcp_nodelay on;

sendfile on;

# SSL VERSION

ssl_protocols SSLv3 TLSv1;

ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;

ssl_prefer_server_ciphers on;

# PATH WEB

location / {

# PASS URL UPSTREAM

proxy_pass http://www.upstream.com.br;

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# BODY SIZE

client_max_body_size 1024M;

client_body_buffer_size 128k;

# TIMEOUT

proxy_connect_timeout 60;

proxy_send_timeout 60;

proxy_read_timeout 60;

proxy_buffers 32 4k;

# IP LIMIT

limit_conn addr 200;

limit_conn perip 50;

limit_conn perserver 50;

#limit_req zone=one burst=50 nodelay;

}

Estatísticas do NGINX:

# STATUS

location /nginx_status {

stub_status on;

access_log off;

# AUTENTICATION

auth_basic "NGINX STATUS";

auth_basic_user_file /etc/nginx/htpasswd;

}

# ERROR PAGE

error_page 404 /404.html;

root /usr/share/nginx/html;

error_page 500 502 503 504 /50x.html;

location = /50x.html {

}

} 

Não deixe de acompanhar uma análise do nosso parceiro Hostinger sobre provedores de hospedagem!

E você, pretende aprender usar melhor seus servidores Web? Conte com os cursos da Escola Linux.

Curso Web Server Apache2 Alta Performance

Curso Online Web Server e Proxy com NGINX

Java: Passado, presente e futuro!
Bancos de Dados Mysql com Alta Performance

Artigos Relacionados

Google Analytics Alternative