Cómo mejorar el rendimiento de los servidores Apache. [ESP-ENG]

in blurtech •  last year 

336.-Apache-Web-Server.png

Esta es una recopilación de configuraciones para mejorar el rendimiento de sus servidores Apache.

Ésta es una de las directivas más importantes, pues determina el número máximo de peticiones simultáneas que Apache puede atender.

La idea es no permitir más conexiones de las que se pueden atender, para evitar usar swap, lo cual disminuye en mucho el rendimiento global. Las peticiones que no se puedan atender se pondrán en cola, según el valor de la directiva ListenBacklog. Se explica cómo se calcula éste número (de forma aproximada) en la documentación oficial, pero se entiende mejor de la fórmula de devside.net:

MaxClients ≈ (RAM - size_all_other_processes)/(size_apache_process)

RAM: se puede usar "free -m" para ver la ram total en MB, o cat /proc/meminfo, entre otras.

Se podrá calcular el tamaño de un proceso httpd con "ps -ylC httpd --sort:rss", el cual mostrará todos los procesos httpd en ejecución, de menor a mayor tamaño, en bytes, para la columna RSS (Resident Set Size: "la memoria no-swap que ha usado, en KB" ). Se podrá ver el tamaño mayor (dividido entre 1024 para tenerlo en MB) como "size_apache_process", o siendo menos severos, usa la siguiente fórmula, la cual calcula la media de los procesos actuales de Apache, ya en MB:

ps -ylC httpd --sort:rss | awk '{SUM += $8; I += 1} END {print SUM/I/1024}'

Siguiendo la regla anterior, se podrá ver el uso de memoria por los procesos que no sean de Apache, con la fórmula descrita a continuación, la cual ya devolverá el resultado en MB:
ps -N -ylC httpd --sort:rss | awk '{SUM += $8} END {print SUM/1024}'

Así por ejemplo:

free -m = 999MB (Mem total)
ps -ylC httpd --sort:rss | awk '{SUM += $8; I += 1} END {print SUM/I/1024}' = 20.5458 (de 10880 a 34084)
ps -N -ylC httpd --sort:rss | awk '{SUM += $8} END {print SUM/1024}' = 343.441

Max_Clients = (999 - 343.441) / 20.5458 = 31,9 => 31 (aproximado)

DirectoryIndex: Aquí se debe especificar un listado de páginas que resolverán como índices, indicando como primera opción la opción más probable. Por ejemplo, en un servidor PHP donde el index suela ser un archivo del estilo index.php especificaremos:

De esta manera, se aceptarán archivos llamados index.php e index.html como archivos que se mostrarán cuando se hace una petición a un dominio sin indicar el fichero que se quiere ver (que es lo habitual).

AllowOverride: Para un mayor rendimiento, deberíamos indicar de forma global, y en todos los virtualhost, "AllowOverride None", para evitar que a cada petición, busque si existe o no un fichero .htaccess en los directorios de la petición (Ej. para un DocumentRoot /var/www, buscará un.htacess en /, otro en /var y otro en /var/www). Por contra, no podremos usar archivos .htaccess en aquellos virtualhost que hayamos configurado así.
apache-allowoverride.

immagine.png

FollowSymLinks y SymLinksIfOwnerMatch:Para evitar llamadas extra en cada petición, se deberá configurar para cada "Directory" de cada VirtualHost, lo siguiente:

'Options +FollowSymLinks -SymLinksIfOwnerMatch'

immagine.png

HostnameLookups: Esta directiva ya viene en las versiones superiores a Apache 1.3, en Off por defecto, y previene así aumentar la latencia de las peticiones HTTP por culpa de la resolución DNS. Si no lo está ya, se recomienda ponerla a Off.

Módulos de Multi-Procesamiento (MPM) .

Apache "viene con una serie de Módulos de Multi-Procesamiento que son los responsables de conectar con los puertos de red de la máquina, aceptar las peticiones, y generar los procesos hijo que se encargan de servirlas".

Básicamente:

Worker: usa múltiples procesos hijos, con múltiples threads cada uno. Cada thread gestiona una conexión a la vez. Generalmente, se recomienda en entornos de alto tráfico.

Prefork: usa múltiples procesos hijos, con un único thread cada uno. Cada proceso gestiona una conexión a la vez. Puede trabajar con módulos de terceros.

[AQUI*(http://chrisgilligan.com/wordpress/apache-config-for-worker-mpm-vs-prefork-mpm/) más información sobre estos MPM. Por cierto, se puede ver con qué MPM estamos trabajando, ejecutando la siguiente línea, lo cual nos devolverá, entre otros, prefork.c o worker.c:

/usr/sbin/apachectl -l

APC.

immagine.png

Si se quiere mejorar el rendimiento de un servidor web, PHP, una muy buena opción es instalarle APC, una caché que optimiza el código PHP intermedio y mejora notablemente el rendimiento del servidor. Sin duda, una utilidad que debería estar instalada en prácticamente cualquier servidor Apache/PHP, ya que tiene una instalación muy sencilla (se encuentra en yum) y efectos notables en el rendimiento.

separador-tux-tux.png

This is a collection of configurations to improve the performance of your Apache servers.

This is one of the most important directives, as it determines the maximum number of simultaneous requests that Apache can handle. The idea is to not allow more connections than can be handled, to avoid using swap, which greatly decreases overall performance. Requests that cannot be handled will be queued, according to the value of the ListenBacklog directive. How this number is calculated (roughly) is explained in the official documentation, but is best understood from the devside.net formula:

MaxClients ≈ (RAM - size_all_other_processes)/(size_apache_process).

RAM: you can use "free -m" to see the total ram in MB, or cat /proc/meminfo, among others.

You can calculate the size of an httpd process with "ps -ylC httpd --sort:rss", which will show all running httpd processes, from smallest to largest, in bytes, for the RSS column (Resident Set Size: "the non-swap memory it has used, in KB" ). You can see the largest size (divided by 1024 to have it in MB) as "size_apache_process", or being less severe, use the following formula, which calculates the average of the current Apache processes, already in MB:

ps -ylC httpd --sort:rss | awk '{SUM += $8; I += 1} END {print SUM/I/1024}'

Following the above rule, you will be able to see the memory usage by non-Apache processes with the formula described below, which will already return the result in MB:

ps -N -ylC httpd --sort:rss | awk '{SUM += $8} END {print SUM/1024}'

So for example:

free -m = 999MB (Mem total)
ps -ylC httpd --sort:rss | awk '{SUM += $8; I += 1} END {print SUM/I/1024}' = 20,5458 (from 10880 to 34084)
ps -N -ylC httpd --sort:rss | awk '{SUM += $8} END {print SUM/1024}' = 343.441

Max_Clients = (999 - 343,441) / 20,5458 = 31.9 => 31 (approximate)

DirectoryIndex: : Here you must specify a list of pages that will resolve as indexes, indicating as first option the most probable option. For example, in a PHP server where the index is usually a file of the index.php style we will specify:

In this way, files named index.php and index.html will be accepted as files to be shown when a request is made to a domain without indicating the file to be seen (which is the usual).

AllowOverride: For a better performance, we should indicate globally, and in all the virtualhost, "AllowOverride None", to avoid that to each request, it looks for if a .htaccess file exists or not in the directories of the request (e.g. for a DocumentRoot /var/www, it will look for a .htacess in /, another one in /var and another one in /var/www). On the other hand, we will not be able to use .htaccess files in those virtualhost that we have configured this way.

AllowOverride: For a better performance, we should indicate globally, and in all the virtualhost, "AllowOverride None", to avoid that at each request, it looks for if a .htaccess file exists or not in the directories of the request (e.g. for a DocumentRoot /var/www, it will look for a .htacess in /, another in /var and another in /var/www). On the other hand, we will not be able to use .htaccess files in those virtualhost that we have configured this way.
apache-allowoverride.

FollowSymLinks y SymLinksIfOwnerMatch:
To avoid extra calls on each request, the following should be configured for each "Directory" of each VirtualHost:

'Options +FollowSymLinks -SymLinksIfOwnerMatch'.

HostnameLookups: This directive is already set to Off by default in versions higher than Apache 1.3, and prevents increasing the latency of HTTP requests due to DNS resolution. If it is not already set to Off, it is recommended to set it to Off.

immagine.png

Multi-Processing Modules (MPM) .

Apache "comes with a series of Multi-Processing Modules that are responsible for connecting to the machine's network ports, accepting requests, and spawning the child processes that are responsible for serving them."

Basically:

Worker: uses multiple child processes, with multiple threads each. Each thread handles one connection at a time. Generally recommended in high traffic environments.

Prefork: uses multiple child processes, with a single thread each. Each process handles one connection at a time. Can work with third party modules.

HERE* more information about these MPMs. By the way, you can see which MPM we are working with, by executing the following line, which will return, among others, prefork.c or worker.c:

/usr/sbin/apachectl -l

APC.

If you want to improve the performance of a web server, PHP, a very good option is to install APC, a cache that optimizes the intermediate PHP code and significantly improves server performance. Undoubtedly, a utility that should be installed in almost any Apache/PHP server, since it has a very simple installation (found in yum) and remarkable effects on performance.

immagine.png

banner-traductor-globe-g308afd03f_1280.jpg

banner-propiedad-imagenes.png

Home Page oficial del proyecto: /Official home page of the project: Apache.

[Download.](Download: https://httpd.apache.org/download.cgi)

Screenshots / Capturas de pantallas:

Apache Screenshots.

Blogs, Sitios Web y Redes Sociales / Blogs, Webs & Social NetworksPlataformas de Contenidos/ Contents Platforms
Mi Blog / My BlogLos Apuntes de Tux
Red Social Twitter / Twitter Social Network@hugorep

separador-firma-rounded-in-photoretrica.png


Posted from https://blurtlatam.intinte.org

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!