全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 7 分钟 ✍️ juanwangdev

容器化数据库调优

数据库容器化需要性能调优,下面介绍 MySQL/PostgreSQL 优化方法。

MySQL 调优

容器配置

YAML
services:
  mysql:
    image: mysql:8.0
    command: >
      --max-connections=200
      --innodb-buffer-pool-size=1G
      --innodb-log-file-size=256M
      --innodb-flush-log-at-trx-commit=2
      --sync-binlog=0      
    volumes:
      - db-data:/var/lib/mysql
    deploy:
      resources:
        limits:
          memory: 2G
          cpus: '2'

关键参数

参数说明推荐值
innodb-buffer-pool-size缓存池大小内存 50-70%
max-connections最大连接数200-500
innodb-log-file-size日志文件大小256M-1G
innodb-flush-method刷盘方式O_DIRECT

PostgreSQL 调优

容器配置

YAML
services:
  postgres:
    image: postgres:15
    command: >
      -c max_connections=200
      -c shared_buffers=512MB
      -c effective_cache_size=2GB
      -c work_mem=16MB
      -c checkpoint_completion_target=0.9
      -c wal_level=replica      
    volumes:
      - db-data:/var/lib/postgresql/data
    deploy:
      resources:
        limits:
          memory: 2G
          cpus: '2'

关键参数

参数说明推荐值
shared_buffers共享缓冲区内存 25%
effective_cache_size有效缓存内存 50-75%
work_mem排序内存16-64MB
maintenance_work_mem维护操作内存256MB
checkpoint_completion_targetCheckpoint 完成目标0.9

WAL 日志优化

PostgreSQL WAL

YAML
# 配置 WAL
command: >
  -c wal_level=replica
  -c max_wal_senders=3
  -c wal_keep_size=1GB
  -c checkpoint_timeout=10min
  -c max_wal_size=2GB
  -c min_wal_size=80MB  

MySQL Binlog

YAML
# 配置 Binlog
command: >
  --log-bin=mysql-bin
  --binlog-format=ROW
  --max-binlog-size=100M
  --expire-logs-days=7
  --sync-binlog=0  # 0=异步,1=同步  

存储优化

Volume 配置

YAML
# 使用本地存储(性能最佳)
volumes:
  db-data:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /data/db

# 或使用 NFS(性能略低)

IO 调度

Bash
# 查看 IO 调度器
cat /sys/block/sda/queue/scheduler

# 设置为 deadline(数据库推荐)
echo deadline > /sys/block/sda/queue/scheduler

内存优化

NUMA 配置

Bash
# 绑定 NUMA 节点
docker run -d \
  --cpuset-cpus="0-7" \
  --cpuset-mems="0" \
  mysql:8.0

HugePages

Bash
# 启用 HugePages
echo "vm.nr_hugepages=1024" >> /etc/sysctl.conf
sysctl -p

# 数据库配置使用
# MySQL: use_large_pages=ON
# PostgreSQL: huge_pages=try

监控指标

指标MySQLPostgreSQL
缓冲命中率Innodb_buffer_pool_hit_rate > 99%blks_hit / (blks_read + blks_hit) > 95%
连接数Threads_connected / max_connectionsnumbackends / max_connections
CheckpointSeconds_Behind_Mastercheckpoints_timel / checkpoints_req
WAL/BinlogBinlog_cache_disk_usewal_write

要点总结

  • MySQL 调优:innodb-buffer-pool-size、max-connections、binlog 配置
  • PostgreSQL 调优:shared_buffers、work_mem、WAL 日志、Checkpoint
  • 存储使用本地 Volume 性能最佳,避免网络存储
  • IO 调度器使用 deadline,启用 HugePages 提升性能
  • 监控缓冲命中率、连接数、Checkpoint 等关键指标

📝 发现内容有误?点击此处直接编辑

← 上一篇 镜像仓库与 K8s 集成
下一篇 → 数据库容器化最佳实践
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库