同樣的硬體,不同的設定,效果可以差出一個量級。以下依序調整核心網路參數、Apache 與 MySQL。所有數值都只是起點,請依實際規格調整。
編輯 /etc/sysctl.conf,若為空白可直接寫入下列內容,否則自行合併:
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.log_martians = 1
net.ipv4.tcp_fin_timeout = 25
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_reordering = 5
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_max_syn_backlog = 2048
net.core.netdev_max_backlog = 1024
net.core.hot_list_length = 256
net.ipv4.tcp_max_tw_buckets = 360000
net.core.rmem_default = 65535
net.core.rmem_max = 8388608
net.ipv4.tcp_rmem = 4096 87380 8388608
net.core.wmem_default = 65535
net.core.wmem_max = 8388608
net.ipv4.tcp_wmem = 4096 65535 8388608
net.ipv4.tcp_mem = 8388608 8388608 8388608
net.core.optmem_max = 40960
若想完全封鎖 ping,再加上 net.ipv4.icmp_echo_ignore_all = 1。存檔後生效:
/sbin/sysctl -p
/sbin/sysctl -w net.ipv4.route.flush=1
這些參數的重點是:放大連線佇列(syn backlog、netdev backlog)、提早回收 TIME_WAIT、啟用 SYN Cookie 抵禦 SYN 洪水、並放大 socket 緩衝區以改善高延遲連結的吞吐。
編輯 /etc/my.cnf:
[mysqld]
connect_timeout=15
interactive_timeout=100
join_buffer_size=1M
key_buffer=128M
max_allowed_packet=16M
max_connections=500
max_connect_errors=10
myisam_sort_buffer_size=64M
read_buffer_size=1M
read_rnd_buffer_size=768K
sort_buffer_size=1M
table_cache=1024
thread_cache_size=100
thread_concurrency=4
wait_timeout=300
query_cache_size=32M
query_cache_limit=1M
query_cache_type=1
skip-innodb
這組值適合 512MB 到 1GB 記憶體;記憶體更大請自行放大 key_buffer 與 query_cache。thread_concurrency 的建議值與 CPU 數相關:單 CPU 設 2,雙 CPU 設 4。要注意記憶體不是越多越好——一旦觸發 swap,整體效能反而急遽下降。另外 query_cache 在後續 MySQL 版本已被標記為即將移除,新環境請改用其他快取策略。
找到並編輯 httpd.conf,重點參數:
KeepAlive On
MaxKeepAliveRequests 1000
KeepAliveTimeout 3
MinSpareServers 8
MaxSpareServers 13
MaxRequestsPerChild 50
把 KeepAliveTimeout 調小,能減少伺服器上的無效等待連結,間接提升負載能力。順帶處理安全相關設定:
ServerSignature Off
ServerTokens ProductOnly
如此一來外人無法輕易探知 Apache 的實際版本,能降低被針對性攻擊的風險。若使用 2.0 以上版本,請自行對照該版本的參數名稱調整。
這些設定能改善負載表現,但沒有放諸四海皆準的最佳值。真正的調校來自監控與實測:先看 mysqladmin extended-status、Apache 的 mod_status 與系統的 vmstat,找出瓶頸再動手,一次只改一項,才能知道哪個改動真的有效。