本文針對 4GB RAM、純 InnoDB、ACID 合規、連接數較少但隊列負載高 的典型場景,提供一份經過實戰驗證的 my.cnf 完整配置模板,並逐項解析核心參數含義與調優邏輯,助你快速構建高效能 MySQL 實例。
/etc/my.cnf — 全域配置$datadir/my.cnf — 實例級配置~/.my.cnf — 用戶級配置所有長選項均可在配置文件使用,執行 mysqld --help 可查看完整支援列表。
[client][client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
# password = your_password # 不建議明文寫入
[mysqld]port = 3306
socket = /var/run/mysqld/mysqld.sock
back_log = 50 # 監聽隊列長度,高併發時調大
max_connections = 100 # 最大連接數(含 1 個 SUPER 預留)
max_connect_errors = 10 # 防暴力破解
table_open_cache = 2048 # 表緩存,配合 open-files-limit
max_allowed_packet = 16M # 單包最大長度,大 BLOB 必調大
thread_stack = 192K # 執行緒堆疊
sort_buffer_size = 8M # ORDER BY / GROUP BY 排序緩存
join_buffer_size = 8M # 全表關聯優化緩存
read_buffer_size = 2M # 全表掃描順序讀緩存
read_rnd_buffer_size = 16M # 隨機讀緩存(如 ref 掃描後排序)
thread_cache_size = 8 # 執行緒複用池,減少創建開銷
query_cache_size = 64M # 查詢緩存(高寫入場景建議關閉)
query_cache_limit = 2M # 單查詢結果緩存上限
tmp_table_size = 64M # 內存臨時表上限,超限轉 MyISAM 磁盤表
max_heap_table_size = 64M # 記憶體表上限,配合 tmp_table_size
default_storage_engine = InnoDB
innodb_buffer_pool_size = 2G # 【核心】設為物理記憶體 70~80%,此處 4G 取 2G
innodb_log_file_size = 256M # Redo log 單檔大小,總量建議 25~100% buffer pool
innodb_log_files_in_group = 3 # Redo log 組檔案數
innodb_log_buffer_size = 8M # Log 寫入緩存,每秒刷盤一次
innodb_flush_log_at_trx_commit = 1 # 1=全 ACID,2=高效能妥協,0=極速但風險
innodb_file_per_table = 1 # 獨立表空間,便於管理與回收空間
innodb_data_file_path = ibdata1:10M:autoextend
innodb_thread_concurrency = 16 # 內核併發控制,0=不限制
innodb_lock_wait_timeout = 120 # 鎖等待超時(秒)
innodb_flush_method = O_DIRECT # 避免雙重緩存,RAID/SSD 必開
innodb_max_dirty_pages_pct = 90 # 臟頁比例觸發刷盤
innodb_additional_mem_pool_size = 16M # 元數據池(5.6.3+ 已廢棄,忽略即可)
log-bin = mysql-bin
server-id = 1
binlog_cache_size = 1M
expire_logs_days = 7 # 自動清理舊 binlog
sync_binlog = 1 # 每次提交同步 binlog,保證不丟失
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2 # 超過 2 秒記錄
log_queries_not_using_indexes = 1 # 記錄未用索引查詢
log_error = /var/log/mysql/error.log
log_warnings = 2 # 記錄連接中斷等警告
key_buffer_size = 32M
myisam_sort_buffer_size = 128M
bulk_insert_buffer_size = 64M
skip-name-resolve # 禁用 DNS 反解,加速連接
skip-external-locking # 禁用外部鎖
transaction_isolation = REPEATABLE-READ
ft_min_word_len = 4 # 全文索引最小詞長
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
[myisamchk]
key_buffer_size = 512M
sort_buffer_size = 512M
[mysqlhotcopy]
interactive-timeout
[mysqld_safe]
open-files-limit = 8192 # 必須 > table_open_cache * 2
innodb_flush_log_at_trx_commit=2 + sync_binlog=100 可大幅提升寫入吞吐,犧牲 1 秒數據安全。thread_cache_size 配合應用端連接池。Innodb_buffer_pool_reads(應趨近 0)、Innodb_log_waits(應為 0)、Threads_created(應緩慢增長)。遷移提醒:修改 innodb_log_file_size 需停庫、刪除舊 ib_logfile* 後重啟;生產環境建議先在測試環境驗證配置兼容性。