You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

actix-web HTTP服务器持续报错Too many open files (os error 24)求助

解决Actix-web "Too many open files (os error 24)" 错误

核心排查方向

你的请求量(12秒200次)远低于当前1000的文件句柄限制,问题根源大概率是句柄未及时释放,而非单纯的上限不足。以下是具体解决步骤:

1. 确认进程实际可用的句柄上限

ulimit -n 仅显示当前shell的限制,进程可能未继承到该配置:

  • 找到服务器进程PID:ps aux | grep [你的进程名]
  • 查看进程实际限制:cat /proc/[PID]/limits | grep "Max open files"
  • 如果实际值远低于1000,需确保进程启动环境继承了ulimit配置(比如用systemd启动的话,要在service文件中添加LimitNOFILE=10000)

2. 调整Actix-web的长连接回收策略

Actix-web 4.x默认keep-alive时长为75秒,若客户端未主动关闭连接,闲置连接会持续占用句柄:

use actix_web::{HttpServer, App};
use std::time::Duration;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new())
        // 缩短长连接闲置时长至10秒,超时自动关闭
        .keep_alive(Some(Duration::from_secs(10)))
        // 或直接关闭长连接:.keep_alive(None)
        .bind(("0.0.0.0", 8080))?
        .run()
        .await
}

3. 排查自定义代码的句柄泄漏

用lsof -p [PID]查看进程所有打开的句柄,重点关注:

  • 大量未关闭的TCP连接(状态为ESTABLISHED/CLOSE_WAIT)
  • 未释放的文件句柄、数据库连接或自定义socket
    确保所有资源在使用后都通过drop或对应关闭方法释放

4. 修正Actix-web的连接限制配置

max_connections是每个worker进程的连接上限,而非全局:

use actix_web::{HttpServer, App};
use num_cpus;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new())
        // 设为CPU核心数,避免过多worker导致总连接数超限
        .workers(num_cpus::get())
        // 每个worker的连接数,总连接数=worker数×max_connections,需小于句柄上限
        .max_connections(200)
        .bind(("0.0.0.0", 8080))?
        .run()
        .await
}

5. 系统层面辅助调整

  • 检查监听队列大小:sysctl net.core.somaxconn,若值小于1024,临时调整:sysctl -w net.core.somaxconn=1024,永久生效需写入/etc/sysctl.conf
  • 确保TCP连接超时回收:调整net.ipv4.tcp_fin_timeout(默认60秒)为15秒:sysctl -w net.ipv4.tcp_fin_timeout=15

内容的提问来源于stack exchange,提问作者Emmanuel Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:23:40