容器化数据库调优
数据库容器化需要性能调优,下面介绍 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_target | Checkpoint 完成目标 | 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
监控指标
| 指标 | MySQL | PostgreSQL |
|---|---|---|
| 缓冲命中率 | Innodb_buffer_pool_hit_rate > 99% | blks_hit / (blks_read + blks_hit) > 95% |
| 连接数 | Threads_connected / max_connections | numbackends / max_connections |
| Checkpoint | Seconds_Behind_Master | checkpoints_timel / checkpoints_req |
| WAL/Binlog | Binlog_cache_disk_use | wal_write |
要点总结
- MySQL 调优:innodb-buffer-pool-size、max-connections、binlog 配置
- PostgreSQL 调优:shared_buffers、work_mem、WAL 日志、Checkpoint
- 存储使用本地 Volume 性能最佳,避免网络存储
- IO 调度器使用 deadline,启用 HugePages 提升性能
- 监控缓冲命中率、连接数、Checkpoint 等关键指标
📝 发现内容有误?点击此处直接编辑