温馨提示×

CentOS怎么优化Docker

小樊
43
2026-08-03 06:41:56
栏目: 智能运维

CentOS(7/8/Stream) 上优化 Docker,可以从 系统内核、存储、网络、资源限制、镜像与容器管理 等多个方面入手。下面给你一套 实用且可落地的优化方案,适合生产环境。


一、系统层面优化(CentOS)

1. 升级系统 & 内核

Docker 对内核版本敏感,建议使用较新内核。

# CentOS 7
yum update -y
reboot

查看内核:

uname -r

建议:

  • CentOS 7:≥ 3.10.0-1160
  • CentOS 8/Stream:≥ 4.18

2. 关闭 swap(非常重要)

Docker 官方强烈建议关闭 swap,否则性能严重下降。

swapoff -a

永久关闭:

vim /etc/fstab
# 注释 swap 行

3. 调整系统参数(sysctl)

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

4. 提高文件描述符限制

vim /etc/security/limits.conf

追加:

* soft nofile 655360
* hard nofile 655360
* soft nproc 655360
* hard nproc 655360

二、Docker 自身优化

1. 使用官方最新稳定版 Docker

不要用 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

2. 优化 Docker 存储驱动(重点)

查看当前驱动:

docker info | grep Storage

推荐顺序:

  1. overlay2(首选)
  2. devicemapper(不推荐)

配置 overlay2(CentOS 7/8 都支持)

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

3. 修改 Docker 数据目录(磁盘优化)

防止 /var/lib/docker 占满系统盘。

vim /etc/docker/daemon.json
{
  "data-root": "/data/docker"
}
systemctl restart docker

4. 日志限制(防止磁盘爆满)

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}

重启 Docker:

systemctl restart docker

三、容器运行优化

1. 限制容器资源(必须)

❌ 不限制 = 风险极高

docker run -d \
  --name app \
  --memory=2g \
  --cpus=2 \
  nginx

查看:

docker stats

2. 使用宿主机网络(高性能场景)

docker run --network host

⚠️ 注意端口冲突


3. 避免频繁创建/销毁容器

  • 使用 长期运行容器
  • 避免 docker run 频繁执行

四、镜像优化

1. 使用轻量基础镜像

✅ 推荐:

  • alpine
  • distroless
  • debian-slim

❌ 避免:

  • ubuntu
  • centos

2. 减少镜像层数

RUN yum install -y xxx && yum clean all

3. 使用 .dockerignore

node_modules
*.log
.git

五、网络优化

1. 使用自定义 bridge 网络

docker network create mynet
docker run --network mynet

2. 调整 MTU(云服务器环境)

{
  "mtu": 1450
}

六、Docker Compose / Swarm 优化(可选)

  • 生产环境 不建议裸 Docker
  • 推荐:
    • Docker Compose(中小型)
    • Kubernetes(大型)

七、性能排查常用命令

docker stats
docker system df
docker system prune -f
iostat -x 1
top

八、推荐的最终 daemon.json 示例

{
  "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
}

九、总结(重点)

关键优化点

  • 关闭 swap
  • overlay2 存储
  • 日志限制
  • 容器资源限制
  • 镜像瘦身
  • 系统参数调优

如果你愿意,我可以:

  • ✅ 针对 CentOS 7 / 8 / Stream 给你定制方案
  • ✅ 针对 Java / Nginx / MySQL / Redis 容器单独优化
  • ✅ 帮你排查 Docker 卡顿、磁盘满、CPU 高 问题

直接告诉我你的 使用场景 即可。

0