在 CentOS(尤其是 CentOS 7/8/Stream) 中,“Context” 优化性能通常取决于你指的是哪一类 Context。下面我按最常见的几种场景分别说明,你可以对照使用。
SELinux 的 context 设置不当,会导致 文件系统访问慢、服务异常、audit 日志暴涨,从而影响性能。
ls -Z
ps -Z
错误示例:
restorecon -Rv /
会导致大量 I/O。
✅ 正确做法:
restorecon -Rv /path/to/app
semanage fcontext -a -t httpd_sys_rw_content_t "/data/www(/.*)?"
restorecon -Rv /data/www
如果确认不是安全问题:
setenforce 0 # 临时关闭(不推荐生产)
或只记录必要日志:
auditctl -D
auditctl -b 8192
systemd service 的 执行上下文 会影响资源使用和启动性能。
[Service]
Type=simple
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=4
CPUWeight=200
MemoryMax=2G
systemctl disable unnecessary.service
systemctl mask unused.service
ulimit -n 65535
ulimit -u 65535
永久生效:
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
systemctl set-property nginx.service CPUQuota=50%
systemctl set-property nginx.service MemoryMax=1G
iptables -L -n --line-number
nft list ruleset
chcon -Rt container_file_t /data
--security-opt label=disable(仅测试)noatime,nodiratime
sysctl -w vm.swappiness=10
sysctl -w net.core.somaxconn=4096
systemctl list-unit-files --type=service | grep enabled
| 现象 | 重点优化 |
|---|---|
| 文件访问慢 | SELinux context |
| 服务启动慢 | systemd context |
| 高并发卡顿 | ulimit / cgroup |
| 容器异常 | SELinux + container context |
| 网络慢 | iptables / nftables |
你可以直接告诉我:
我可以给你 一条命令级优化方案。