温馨提示×

centos ulimit怎么配置

小樊
52
2026-09-30 05:41:19
栏目: 智能运维

在 CentOS 中,ulimit 用于限制 用户/进程 可使用的系统资源(如文件句柄数、进程数、内存等)。配置方式主要分为 临时配置 和 永久配置 两类,下面按常见使用场景说明。


一、临时配置(当前会话生效)

1. 查看当前限制

ulimit -a

常用参数:

  • -n:打开文件数(file descriptors)
  • -u:最大用户进程数
  • -s:栈大小
  • -c:core 文件大小
  • -m / -v:内存限制(部分系统不支持)

2. 临时修改(仅当前 shell 及子进程)

ulimit -n 65535
ulimit -u 4096

⚠️ 重启或退出会话后失效


二、永久配置(推荐生产环境使用)

方式一:通过 /etc/security/limits.conf(最常用)

编辑文件:

vi /etc/security/limits.conf

示例配置

* soft nofile 65535
* hard nofile 65535
* soft nproc 4096
* hard nproc 4096

格式说明:

<用户/组> <soft/hard> <资源类型> <值>

常见资源:

  • nofile:打开文件数
  • nproc:进程数
  • core:core 文件大小
  • memlock:锁定内存

对特定用户

www soft nofile 100000
www hard nofile 100000

方式二:使用 /etc/security/limits.d/(推荐)

CentOS 默认会加载该目录下的 .conf 文件:

vi /etc/security/limits.d/20-nofile.conf

内容示例:

* soft nofile 65535
* hard nofile 65535

数字前缀决定加载顺序,越小越先加载


方式三:systemd 服务(CentOS 7+ 特别注意)

如果是 systemd 管理的服务(如 nginx、mysql),limits.conf 可能不生效。

修改 service 文件

systemctl edit nginx

添加:

[Service]
LimitNOFILE=65535
LimitNPROC=4096

重新加载:

systemctl daemon-reload
systemctl restart nginx

或直接修改:

vi /usr/lib/systemd/system/nginx.service

三、系统级文件句柄总限制

查看系统最大 fd

cat /proc/sys/fs/file-max

临时修改

sysctl -w fs.file-max=2000000

永久修改

vi /etc/sysctl.conf
fs.file-max = 2000000
sysctl -p

四、验证是否生效

普通用户

su - username
ulimit -n

systemd 服务

cat /proc/<pid>/limits

五、常见问题

1. 修改后不生效?

  • 是否重新登录
  • 是否是 systemd 服务
  • PAM 是否启用(/etc/pam.d/login 中是否有 pam_limits.so)

2. root 用户仍受限?

部分资源对 root 也受 limits.conf 限制,需显式配置:

root soft nofile 65535
root hard nofile 65535

如果你能说明 具体场景(如:Web 服务、数据库、Docker、高并发),我可以给你更精确的配置示例。

0 踩