php教程 php手册 Fine tuning a Linux Apache MySQL PHP (LAMP) server

Fine tuning a Linux Apache MySQL PHP (LAMP) server

Jun 06, 2016 pm 07:45 PM
apache linux mysql

I started to write this post many weeks ago and finally publish it even if it’s not totally finish. It is just a little feedback about tuning a full LAMP server with some user traffic and services load. Important thing to notice is that a

I started to write this post many weeks ago and finally publish it even if it’s not totally finish. It is just a little feedback about tuning a full LAMP server with some user traffic and services load. Important thing to notice is that all stuff in this post is NOT THE SOLUTION. You will probably have to tune little more for adapt all this to your personal server usage, server load, development & architecture. So, use those tips as a kind of inspiration instead of an “how to”. Don’t forget that when you do such tuning, take care to keep a backup of your previous configuration files.

We will try to tune the following server :

  • Current OS : Debian GNU Linux Kernel 2.4.32 ipv4 + GRSEC
  • 1Go RAM DDR
  • Intel(R) Celeron(R) CPU 2.66GHz
  • SWAP 512Mo
  • 3Go on / and 226Go on /home
  • Running services are Qmail, Bind9, mrtg, Apache 2.2.2, PHP 5.1.4, MySQL 5.0.21


The best way for tuning a server is to have dedicated services on one server and so, having multiple server especially for MySQL and Apache.

We were runing a heavy website with DotClear and the heavy PhpADS with all its stuff (geoip, all counters, etc.)
The server up to a load of 114 in some peak with a swap totally used ! And so.. a big freeze of services… 70k mails/day , 110k pv/day, 12k v/day, 47 sql queries/sec

In fact, services weren’t so loaded but the box was crashing a lot and swapping often without using too much CPU.

First things that I do was to change the Linux Kernel from a 2.4.32 to a 2.6.18. Lot of things were improves in 2.6. I convey you to take a look at those posts :
http://www-128.ibm.com/developerworks/linux/library/l-web26/
http://developer.osdl.org/craiger/hackbench/
http://kerneltrap.org/node/903

After this update, I take the time to update all version software for using a MySQL 5.0.27, PHP 5.2 etc. Without looking at the changelogs, bugfixes will still help us :-)
After this, we will tune our software configuration that still use default values (this is really bad ! :) then we will tune a little the kernel without recompile a new one.

  • Apache 2.2.2 Prefork

Our HTTPD is using some modules as url rewriting, server info, php5, GeoIP and other basic modules. We could optimize much more by using an Apache 2.2.3 Worker and only useful modules or even more delivering static pages and using proxy for dynamic pages. All this depend on your developments and your server usage. Here we will only focus on the Apache Prefork.
Nowadays, it’s important to keep active the KEEPALIVE functionality. This will increase the speed of delivring pages for lot of modern browsers (it’s supported by ie, firefox, safari, opera, etc.). The only thing is to touch a little to the default value. In fact, if your keepalive time out is too big, you will keep an entire apache slot open for a user that is probably gone ! A 4 seconds timeout is enough for delivering a full web page and take care of any network congestion. MaxKeepAliveRequests is used to define the maximum number of request manage by an apache slot during a keepalive session. Except if you have lot of pictures to load on your web pages you don’t really need to have a big value at this state.

KeepAlive On
KeepAliveTimeout 4
MaxKeepAliveRequests 500

As I don’t have lot of memory available on the server I ‘m constraint to decrease drastically the number of running servers from 150 to 60. As I have an apache using approximatly 13Mo of memory (withdraw 3Mo of shared memory), I need approximately 600 Mo of available memory when all the apache child process are running. We have to consider, for our further tuning, that this memory is used. It’s really important in our case to dedicate memory for avoid to swap too much and lost the box in a freeze. you can follow your memory usage by using TOP and looking for your apache/httpd process. (Do a quick “man top” for know more). If you have little more free memory you can take a look to the apache documentation for further tuning.

ServerLimit 60
MaxClients 60

Our server is often overload, with lot of traffic. When I need to restart the apache, or in case of any crashes the apache server start with only 5 Child server process and will add new one 1 second later, 2 new child 2 second later, 4 new at the third second, etc. It’s really too long when you are in a peak ! So, I configured StartServers for let us start directly with 30 child Server process. That will help us to deliver quickly the clients and minimize the impact of the server restart.

MinSpareServers and MaxSpareServers is used in same way as StartServer. When your apache server isn’t load, there is idle child waiting for connection. It’s not usefull to have all your child still open but, In case of a new peak the best way to minimize its impact on your server is to deliver web pages as quick as possible. So keeping some idle Child Process still waiting for client isn’t so stupid. Furthermore in case of our touchy server we consider to be able to allocate 600Mo of RAM. So, We can use it even if it’s for idle Child Process as we dedicate this RAM for apache. For avoid any module Memory Leak, and having fully available Child I set the MaxRequestPerChild to 1000, that mean that each 1000 request, the child will be kill and Apache Server will spare a new one. You’ll probably have to set this value to a higher number. It’s depend of the structure of your web page. You will have to monitor a little your server after those change for being sure to don’t have too much child kill/spare instead of delivering web pages.

StartServers 30
MinSpareServers 30
MaxSpareServers 30
MaxRequestsPerChild 1000

Follow some security issue, we don’t display too much information about our server. As we don’t need the reverse lookup on the client ip, we keep the default value of HostnameLookups to Off and by this way we save some network traffic and server load.

ServerTokens Prod
ServerSignature Off
HostnameLookups Off

  • PHP 5.1.4

For perform our page generation and save some cpu we use the php extensioneaccelerator. Take a look at the documentation for install it.
We dedicate 32Mo of our RAM for eaccelerator (shm_size) and will use it with shared memory and file cache (“shm_and_disk” value for keys, sessions and content variable). (Memory is really useful in our case, because of all the mails, apache log and MySQL disk access that generate too much i/o and slow down considerably all the server). As we don’t change often the php script on the server we don’t need to use thecheck_mtime functionality. When set to “1″, that will do a stat on the php script for checking of last modification date We don’t need this because we want to save disk access and we don’t have so many updates on the running scripts. We just have to clean the cache directory after an update.

eaccelerator.shm_size=”32″
eaccelerator.cache_dir=”/www/tmp/eaccelerator”
eaccelerator.enable=”1″
eaccelerator.optimizer=”1″
eaccelerator.check_mtime=”0″
eaccelerator.debug=”0″
eaccelerator.filter=”"
eaccelerator.shm_max=”0″
eaccelerator.shm_ttl=”3600″
eaccelerator.shm_prune_period=”1″
eaccelerator.shm_only=”0″
eaccelerator.compress=”1″
eaccelerator.compress_level=”9″
eaccelerator.keys = “shm_and_disk”
eaccelerator.sessions = “shm_and_disk”
eaccelerator.content = “shm_and_disk”

  • MySQL 5.0.24

As I don’t manage how has been coding many of running script, I decrease all the timeout MySQL connection for avoid congestion. Then I increase the number off simultaneous MySQL connection as we had lot of “Too many connection” error message.

wait_timeout=6
connect_timeout=5
interactive_timeout=120
max_connections = 500
max_user_connections = 500

Now we change the touchiest part of the MySQL configuration : The RAM usage. It’s touchy because a bad value can really decrease your server performance and result in a big server swap. After some test I decrease the table cache and the key buffer cache to 256Mo. In fact we don’t have so many available ram as we had 600Mo for ourHTTPD and we have lot of other services running. I tried to set it up little higher, hopping that the swap won’t be to big, but in fact, due to our i/o load the swap were totaly not a good thing for MySQL :-)

If you are using MYISAM tables I suggest you to use the “concurrent_insert=2” that will really increase your server performance in many case. MYISAM use table lock, with concurrent insert, the engine will sometime bypass the lock and allow INSERT and SELECT to run concurrently. We also disable all engine that is not used (innodb, bdb). Take a look at the MySQL documentation for better tuning.

join_buffer_size=1M
sort_buffer_size=1M
read_buffer_size=1M
read_rnd_buffer_size=1M
table_cache=256M
max_allowed_packet=4M

key_buffer=256M
key_buffer_size=256M
thread_cache=256M
thread_concurrency=2
thread_cache_size=40
thread_stack=128K

concurrent_insert=2

query_cache_limit=1M
query_cache_size=256M
query_cache_type=1
skip-bdb
skip-innodb

  • Linux Kernel 2.6.18

Here is a touchy part of our tuning, we will try to perform the Linux Kernel behavior with our server load for save some memory and avoid too much swap. Furthermore, has we done a great stuff above this part, we have to manage more TCP connection and support correctly the peak. We will use the command “sysctl” for doing our update on values.

# display value of a variable or group of variable
sysctl [-n] [-e] variable …
# set a new value toe the specified variable
sysctl [-n] [-e] [-q] -w variable=value …
# display all the variable
sysctl [-n] [-e] -a
# load a sysctl config file
sysctl [-n] [-e] [-q] -p (default /etc/sysctl.conf)

For our test we will create a test config file “/etc/sysctl.conf.testing” and we will load it by using the following command line :

sysctl -p /etc/sysctl.conf.testing

When you will be glad of your change you could rename the file for “/etc/sysctl.conf”. All the sysctl variable are documented with the Kernel Sources. I suggest you to download the documentation corresponding to your kernel version and read it carefully if you decide to change some values.
A really good article on Security Focus give us some key for minimize the impact of aSYN ATTACK / SYN SPOOFING. In this goal we activate the syncookies and the route validation

net.ipv4.conf.default.rp_filter=1
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_synack_retries=3
net.ipv4.tcp_syn_retries=3

As we had some swap troubles, important thing to do is to change the value ofvm.swappiness where the default value is 60. This variable control how much the kernel should favor swapping out applications, its value can be 0 to 100. I set it to 10 for minimize the swap.

vm.swappiness=10

We upgrade the max backlog for support more TCP traffic and we change the congestion control algorithm to BIC. The Linux Kernel support lot of congestion algorithm like Reno (default one), htcp, vegas, westwood, etc.

net.core.netdev_max_backlog=2500 # Interface buffering
net.ipv4.tcp_max_syn_backlog=4096
net.core.somaxconn=1024 # Limit of socket listen() backlog. Default is 128.
net.ipv4.tcp_congestion_control=bic

For avoid to have a big TCP queue and so memory usage for not really active connection I decrease some TCP timeout and force the kernel to recycle quickly tcp connection. We don’t cache the value of ssthresh (Slow Start Threshold) for avoid to impact a given host to have a reduced ssthresh for all is next connections.

net.ipv4.tcp_keepalive_time=900
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_max_orphans=16384
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_rfc1337=1
net.ipv4.tcp_no_metrics_save=1

It’s critical to use the optimal SEND and RECEIVE socket buffer size for the link you are using. In our case we have a 100Mbits link connection. So for a better TCP connection and congestion control we had to increase the TCP Buffer. You can read more about this here.

net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.ipv4.tcp_rmem=4096 87380 16777216
net.ipv4.tcp_wmem=4096 65536 16777216

  • That’s all folks !

Now, this server support twice more traffic load. Technical aspect was our traffic growth bottleneck. Lot of other tuning could be done for better performance (on i/o and disk access, other kernel options, compile a new kernel, using apache worker, etc.). This post was just some clues about how to tune your servers. One important thing to don’t forget is whatever you tune on your server, that will never be enough if you have a bloody developed programs running on it !


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DeepSeek 웹 버전 입구 DeepSeek 공식 웹 사이트 입구 DeepSeek 웹 버전 입구 DeepSeek 공식 웹 사이트 입구 Feb 19, 2025 pm 04:54 PM

DeepSeek은 웹 버전과 공식 웹 사이트의 두 가지 액세스 방법을 제공하는 강력한 지능형 검색 및 분석 도구입니다. 웹 버전은 편리하고 효율적이며 설치없이 사용할 수 있습니다. 개인이든 회사 사용자이든, DeepSeek를 통해 대규모 데이터를 쉽게 얻고 분석하여 업무 효율성을 향상시키고 의사 결정을 지원하며 혁신을 촉진 할 수 있습니다.

MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 Dec 09, 2024 am 11:42 AM

MySQL 8.4(2024년 최신 LTS 릴리스)에 도입된 주요 변경 사항 중 하나는 "MySQL 기본 비밀번호" 플러그인이 더 이상 기본적으로 활성화되지 않는다는 것입니다. 또한 MySQL 9.0에서는 이 플러그인을 완전히 제거합니다. 이 변경 사항은 PHP 및 기타 앱에 영향을 미칩니다.

DeepSeek을 설치하는 방법 DeepSeek을 설치하는 방법 Feb 19, 2025 pm 05:48 PM

Docker 컨테이너를 사용하여 사전 컴파일 된 패키지 (Windows 사용자의 경우)를 사용하여 소스 (숙련 된 개발자)를 컴파일하는 것을 포함하여 DeepSeek를 설치하는 방법에는 여러 가지가 있습니다. 공식 문서는 신중하게 문서를 작성하고 불필요한 문제를 피하기 위해 완전히 준비합니다.

Bitget 공식 웹 사이트 설치 (2025 초보자 안내서) Bitget 공식 웹 사이트 설치 (2025 초보자 안내서) Feb 21, 2025 pm 08:42 PM

Bitget은 스팟 거래, 계약 거래 및 파생 상품을 포함한 다양한 거래 서비스를 제공하는 Cryptocurrency 교환입니다. 2018 년에 설립 된이 교환은 싱가포르에 본사를두고 있으며 사용자에게 안전하고 안정적인 거래 플랫폼을 제공하기 위해 노력하고 있습니다. Bitget은 BTC/USDT, ETH/USDT 및 XRP/USDT를 포함한 다양한 거래 쌍을 제공합니다. 또한 Exchange는 보안 및 유동성으로 유명하며 프리미엄 주문 유형, 레버리지 거래 및 24/7 고객 지원과 같은 다양한 기능을 제공합니다.

Ouyi OKX 설치 패키지가 직접 포함되어 있습니다 Ouyi OKX 설치 패키지가 직접 포함되어 있습니다 Feb 21, 2025 pm 08:00 PM

세계 최고의 디지털 자산 거래소 인 Ouyi Okx는 이제 안전하고 편리한 거래 경험을 제공하기 위해 공식 설치 패키지를 시작했습니다. OUYI의 OKX 설치 패키지는 브라우저를 통해 액세스 할 필요가 없습니다. 설치 프로세스는 간단하고 이해하기 쉽습니다. 사용자는 최신 버전의 설치 패키지를 다운로드하고 설치를 단계별로 완료하면됩니다.

Gate.io 설치 패키지를 무료로 받으십시오 Gate.io 설치 패키지를 무료로 받으십시오 Feb 21, 2025 pm 08:21 PM

Gate.io는 사용자가 설치 패키지를 다운로드하여 장치에 설치하여 사용할 수있는 인기있는 cryptocurrency 교환입니다. 설치 패키지를 얻는 단계는 다음과 같습니다. Gate.io의 공식 웹 사이트를 방문하고 "다운로드"를 클릭하고 해당 운영 체제 (Windows, Mac 또는 Linux)를 선택하고 컴퓨터에 설치 패키지를 다운로드하십시오. 설치 중에 항 바이러스 소프트웨어 또는 방화벽을 일시적으로 비활성화하여 원활한 설치를 보장하는 것이 좋습니다. 완료 후 사용자는 GATE.IO 계정을 만들려면 사용을 시작해야합니다.

Ouyi Exchange 다운로드 공식 포털 Ouyi Exchange 다운로드 공식 포털 Feb 21, 2025 pm 07:51 PM

OKX라고도하는 Ouyi는 세계 최고의 암호 화폐 거래 플랫폼입니다. 이 기사는 OUYI의 공식 설치 패키지 용 다운로드 포털을 제공하여 사용자가 다른 장치에 OUYI 클라이언트를 설치할 수 있도록합니다. 이 설치 패키지는 Windows, Mac, Android 및 iOS 시스템을 지원합니다. 설치가 완료되면 사용자는 OUYI 계정에 등록하거나 로그인하고 암호 화폐 거래를 시작하며 플랫폼에서 제공하는 기타 서비스를 즐길 수 있습니다.

Gate.io 공식 웹 사이트 등록 설치 패키지 링크 Gate.io 공식 웹 사이트 등록 설치 패키지 링크 Feb 21, 2025 pm 08:15 PM

Gate.io는 광범위한 토큰 선택, 낮은 거래 수수료 및 사용자 친화적 인 인터페이스로 유명한 호평을받는 암호 화폐 거래 플랫폼입니다. Gate.io는 고급 보안 기능과 우수한 고객 서비스를 통해 트레이더에게 신뢰할 수 있고 편리한 암호 화폐 거래 환경을 제공합니다. Gate.io에 가입하려면 제공된 링크를 클릭하여 공식 등록 설치 패키지를 다운로드하여 Cryptocurrency 거래 여정을 시작하십시오.

See all articles