Total Pageviews

Friday 28 September 2012

高并发linux内核网络参数调优

调整linux(ubuntu8.0.4)内核参数以便满足高并发访问,解决大量time_wait和syn攻击问题:
1 sudo vi /etc/sysctl.conf
在最下面编辑添加:
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.route.gc_timeout = 100
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_max_syn_backlog = 262144
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_mem = 94500000 915000000 927000000
保存退出
2 sudo /sbin/sysctl -p
立刻生效(实践中有遇到不能立刻生效的,需要重启机器才能生效)
使用如下命令监控当前各状态连接:
1netstat -n | awk ‘/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}’
2 cat /proc/net/sockstat
3 查看是否有异常日志:dmesg
4 查看当前IP个数和每IP连接数:
netstat -an | grep 80 | awk ‘{print $5}’ | awk ‘BEGIN {FS=”:”} NF==2 {print $1}NF==5{print $4}’ | sort | uniq -c | sort -n
#获取单前会话连接数
grep -o “src=.*dport=[0-9]\{1,5\}” /proc/net/ip_conntrack |awk ‘{print $1}’|awk -F= ‘{print $2}’ |sort |uniq -c | sort -n | awk ‘(sum += $1); END{print “sum = “sum}’
默认值恢复:
net.ipv4.tcp_fin_timeout = 60
net.ipv4.tcp_keepalive_time = 7200
net.ipv4.route.gc_timeout = 300
net.ipv4.ip_local_port_range = 32768 61000
net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_syn_retries = 5
net.ipv4.tcp_synack_retries = 5
net.ipv4.tcp_max_syn_backlog = 1024
net.core.netdev_max_backlog = 1000
net.core.somaxconn = 128
net.ipv4.tcp_mem = 853440 1137920 1706880
以上配置在实际生产环境中单机1.7w连接数情况下nginx工作正常。