@ユメイ1 周前
12/6
16:49
# 0. 确保 BBR 模块开机自启 ---
echo "正在配置 BBR 模块持久化..."
if ! grep -q "tcp_bbr" /etc/modules-load.d/modules.conf 2>/dev/null; then
echo "tcp_bbr" | sudo tee -a /etc/modules-load.d/modules.conf > /dev/null
fi
sudo modprobe tcp_bbr
# 1. 写入优化配置到 /etc/sysctl.d/99-tuning.conf
# 使用 99- 前缀确保优先级最高
sudo tee /etc/sysctl.d/99-tuning.conf > /dev/null <<EOF
# --- 系统级文件限制 ---
fs.file-max = 2000000
fs.inotify.max_user_instances = 8192
# --- 拥塞控制 (需内核 >= 4.9) ---
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
# --- 丢包恢复与重传优化 ---
net.ipv4.tcp_sack = 1
net.ipv4.tcp_dsack = 1
# 开启 MTU 探测 (解决巨型帧丢包)
net.ipv4.tcp_mtu_probing = 1
net.ipv4.tcp_base_mss = 1024
# --- IP 转发 (Docker/K8s/路由转发必开) ---
net.ipv4.ip_forward = 1
net.ipv4.conf.all.forwarding = 1
net.ipv4.conf.default.forwarding = 1
net.ipv6.conf.all.forwarding = 1
net.ipv6.conf.default.forwarding = 1
# --- Keepalive (快速清理死连接) ---
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 15
net.ipv4.tcp_keepalive_probes = 5
# --- 核心缓冲区 (适合 8GB+ 内存服务器) ---
net.core.rmem_max = 33554432
net.core.wmem_max = 33554432
net.ipv4.tcp_rmem = 4096 1048576 33554432
net.ipv4.tcp_wmem = 4096 1048576 33554432
net.ipv4.udp_rmem_min = 16384
net.ipv4.udp_wmem_min = 16384
# --- 特性优化 ---
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_moderate_rcvbuf = 1
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_notsent_lowat = 16384
# --- 队列与并发 ---
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 300000
EOF
# 2. 使配置生效 (使用 --system 读取所有配置文件)
echo "正在应用 sysctl 配置..."
sudo sysctl --system
# 3. 设置用户级文件限制
# 注意:limits.conf 的修改需要用户【重新登录】或【重启服务】才能生效
echo "正在更新 limits.conf..."
sudo bash -c 'cat >> /etc/security/limits.conf <<EOF
* soft nofile 1000000
* hard nofile 1000000
root soft nofile 1000000
root hard nofile 1000000
EOF'
# 4. 开启 PAM 限制模块 (确保 limits.conf 生效)
# 这一步在某些精简版系统(如 Debian/Ubuntu)上是必须的
if [ -f /etc/pam.d/common-session ]; then
grep -q "pam_limits.so" /etc/pam.d/common-session || echo "session required pam_limits.so" | sudo tee -a /etc/pam.d/common-session
fi
echo "优化完成。请重新登录终端或重启服务器以确保文件描述符限制生效。"
