在 Debian 系统中,限制进程资源可以从临时限制(运行单个命令)、用户/组级限制(长期)、以及**系统化(systemd / cgroup)**几个层面来做。下面按常见场景说明。
ulimit -a
ulimit -u 100 # 最大进程数
ulimit -n 1024 # 最大文件描述符
ulimit -v 524288 # 虚拟内存(KB)
ulimit -m 262144 # 物理内存(KB,部分系统不生效)
ulimit -t 60 # CPU 时间(秒)
ulimit -f 1048576 # 文件大小(KB)
⚠️ 只对当前 shell 及其子进程有效,重启失效。
sudo nano /etc/security/limits.conf
www-data soft nproc 200
www-data hard nproc 300
appuser soft nofile 4096
appuser hard nofile 8192
说明:
soft:软限制(可临时超过)hard:硬限制(不可超过)grep pam_limits /etc/pam.d/common-session
应有:
session required pam_limits.so
✅ 适用于 SSH / 登录用户,不适用于 systemd 服务
sudo systemctl edit yourapp.service
[Service]
MemoryMax=512M
MemoryHigh=400M
TasksMax=100
CPUQuota=50%
IOWeight=100
sudo systemctl daemon-reload
sudo systemctl restart yourapp
✅ 这是 Debian 现代系统最推荐方式
sudo apt install cgroup-tools
sudo cgcreate -g memory,cpu:/mygroup
sudo cgset -r memory.limit_in_bytes=512M mygroup
sudo cgset -r cpu.cfs_quota_us=50000 mygroup
sudo cgexec -g memory,cpu:/mygroup mycommand
✅ 适合批量进程、容器式隔离
nice -n 10 ./myprogram
sudo apt install cpulimit
sudo cpulimit -p 1234 -l 30
⚠️ 非硬限制,可能被绕过
tc(流量控制)iptables / nftables 限速--network 限制)| 场景 | 推荐方式 |
|---|---|
| 临时运行命令 | ulimit |
| 限制登录用户 | limits.conf |
| 后台服务 | systemd |
| 多进程/容器 | cgroups |
| CPU 软控 | nice / cpulimit |
如果你能说明 限制什么资源(CPU / 内存 / 进程数 / 网络)以及使用场景(服务 / 脚本 / 用户),我可以给你更精确的配置示例。