在 CentOS(以及大多数 Linux 发行版)中,ulimit 用于控制用户进程可使用的系统资源上限,如文件描述符数、进程数、内存等。优化 ulimit 通常是为了解决高并发、数据库连接、中间件(如 Nginx、Redis、ES、Kafka)等场景下的资源不足问题。
下面按常见场景 + 配置方式 + 验证方法系统说明。
ulimit -a
常见关键项:
-n:open files(文件描述符,最重要)-u:max user processes(进程/线程数)-s:stack size-c:core file size-m / -v:内存限制(现代系统通常不限制)查看当前 shell 限制:
ulimit -n
ulimit -u
只对当前 shell 生效:
ulimit -n 65535
ulimit -u 65535
退出登录即失效。
/etc/security/limits.confvi /etc/security/limits.conf
示例(针对所有用户或指定用户):
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
指定用户(如 appuser):
appuser soft nofile 100000
appuser hard nofile 100000
appuser soft nproc 65535
appuser hard nproc 65535
✅ 说明:
soft:警告值hard:硬上限nofile:文件描述符nproc:进程/线程数CentOS 7/8 会使用:
/etc/security/limits.d/20-nproc.conf
可能存在:
* soft nproc 4096
这会覆盖 limits.conf,建议修改或新建:
vi /etc/security/limits.d/20-nproc.conf
* soft nproc 65535
* hard nproc 65535
如果你是 CentOS 7/8 + systemd(如 Nginx、MySQL、Java 服务),limits.conf 可能不生效!
systemctl edit nginx
写入:
[Service]
LimitNOFILE=100000
LimitNPROC=65535
然后:
systemctl daemon-reload
systemctl restart nginx
vi /etc/systemd/system.conf
DefaultLimitNOFILE=100000
DefaultLimitNPROC=65535
systemctl daemon-reexec
即使 ulimit 调大,内核也可能不够:
cat /proc/sys/fs/file-max
临时:
sysctl -w fs.file-max=1000000
永久:
vi /etc/sysctl.conf
fs.file-max = 1000000
sysctl -p
| 场景 | nofile | nproc |
|---|---|---|
| Web / Nginx | 65535~100000 | 65535 |
| MySQL | 65535 | 65535 |
| Redis | 65535 | 65535 |
| Elasticsearch | 65535~100000 | 65535 |
| Java 微服务 | 100000+ | 65535 |
ulimit -n
ulimit -u
cat /proc/<pid>/limits
❌ 改了 limits.conf 但 systemd 服务不生效
❌ 只改 soft 不改成 hard
❌ 忘了 limits.d 覆盖
❌ Java 程序仍报 “Too many open files”
如果你愿意,可以告诉我:
我可以给你精确到行的配置方案。