在 CentOS(7/8/Stream) 上优化 Docker,可以从 系统内核、存储、网络、资源限制、镜像与容器管理 等多个方面入手。下面给你一套 实用且可落地的优化方案,适合生产环境。
Docker 对内核版本敏感,建议使用较新内核。
# CentOS 7
yum update -y
reboot
查看内核:
uname -r
建议:
- CentOS 7:≥ 3.10.0-1160
- CentOS 8/Stream:≥ 4.18
Docker 官方强烈建议关闭 swap,否则性能严重下降。
swapoff -a
永久关闭:
vim /etc/fstab
# 注释 swap 行
vim /etc/sysctl.conf
推荐配置:
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
vm.swappiness = 0
vm.max_map_count = 262144
fs.file-max = 655360
生效:
sysctl -p
vim /etc/security/limits.conf
追加:
* soft nofile 655360
* hard nofile 655360
* soft nproc 655360
* hard nproc 655360
不要用 CentOS 自带旧版 docker。
yum remove docker* -y
yum install -y yum-utils
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install -y docker-ce docker-ce-cli containerd.io
查看当前驱动:
docker info | grep Storage
✅ 推荐顺序:
overlay2(首选)devicemapper(不推荐)mkdir -p /etc/docker
vim /etc/docker/daemon.json
{
"storage-driver": "overlay2",
"storage-opts": [
"overlay2.override_kernel_check=true"
]
}
重启:
systemctl daemon-reexec
systemctl restart docker
防止 /var/lib/docker 占满系统盘。
vim /etc/docker/daemon.json
{
"data-root": "/data/docker"
}
systemctl restart docker
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
}
}
重启 Docker:
systemctl restart docker
❌ 不限制 = 风险极高
docker run -d \
--name app \
--memory=2g \
--cpus=2 \
nginx
查看:
docker stats
docker run --network host
⚠️ 注意端口冲突
docker run 频繁执行✅ 推荐:
alpinedistrolessdebian-slim❌ 避免:
ubuntucentosRUN yum install -y xxx && yum clean all
.dockerignorenode_modules
*.log
.git
docker network create mynet
docker run --network mynet
{
"mtu": 1450
}
docker stats
docker system df
docker system prune -f
iostat -x 1
top
{
"storage-driver": "overlay2",
"data-root": "/data/docker",
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
},
"live-restore": true,
"max-concurrent-downloads": 5
}
✅ 关键优化点
如果你愿意,我可以:
直接告诉我你的 使用场景 即可。