温馨提示×

centos ulimit文件数限制

小樊
50
2026-10-11 22:31:12
栏目: 智能运维

在 CentOS 中,文件数限制(open files / file descriptors)通常是通过 ulimit 来查看和设置的,分为临时生效和永久生效两种方式。


一、查看当前文件数限制

ulimit -n

查看某用户的限制(如 mysql):

su - mysql -c 'ulimit -n'

查看系统级限制:

cat /proc/sys/fs/file-max

二、临时修改(当前会话生效)

ulimit -n 65535

⚠️ 只对当前 shell 及子进程有效,重启或重新登录后失效。


三、永久修改(推荐)

1️⃣ 修改 /etc/security/limits.conf

vi /etc/security/limits.conf

添加以下内容(示例):

* soft nofile 65535
* hard nofile 65535

或针对指定用户:

nginx soft nofile 65535
nginx hard nofile 65535

说明:

  • soft:软限制(可临时超过,但会警告)
  • hard:硬限制(不能超过)
  • nofile:打开文件数

2️⃣ 确保 PAM 生效(一般默认已开启)

检查:

grep pam_limits /etc/pam.d/login

应有:

session required pam_limits.so

3️⃣ systemd 服务(CentOS 7+ 重点)

如果是 systemd 管理的服务(如 nginx、mysql),limits.conf 可能不生效,需要单独配置:

方法一:修改 service 文件

systemctl edit nginx

添加:

[Service]
LimitNOFILE=65535

然后:

systemctl daemon-reload
systemctl restart nginx

方法二:全局 systemd 限制

vi /etc/systemd/system.conf
DefaultLimitNOFILE=65535
systemctl daemon-reexec

四、系统级最大文件数

# 查看
cat /proc/sys/fs/file-max

# 临时修改
sysctl -w fs.file-max=1000000

# 永久修改
vi /etc/sysctl.conf
fs.file-max = 1000000
sysctl -p

五、验证

# 当前进程
cat /proc/<pid>/limits | grep "Max open files"

# 服务
systemctl show nginx | grep LimitNOFILE

如果你有 具体场景(如 Nginx、MySQL、Docker、高并发服务),可以告诉我,我可以给你更精确的配置方案。

0 踩