首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL 5.6 低內存 VPS 啟動優化:精簡 my.cnf 將佔用從 400MB 降至 100MB 以內

     編輯:MySQL 資料庫相關知識

問題背景

512 MB 記憶體 VPS,安裝 Nginx + PHP-FPM 後剩餘約 150 MB。MySQL 5.6 預設配置啟動即佔用 ~400 MB,導致 OOM Killer 強制終止進程。需精簡配置釋放記憶體。

核心調整三參數(立竿見影)

performance_schema_max_table_instances = 200
table_definition_cache = 200
table_open_cache = 128

這三個參數直接控制 Performance Schema 與表緩存的記憶體上限,預設值過大是 5.6 版本在小記憶體機器上的首殺因素。

完整精簡版 my.cnf 範本(512 MB 適用)

[client]
port = 3306
socket = /tmp/mysql.sock

[mysqld]
port = 3306
socket = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql
pid-file = /data/mysql/mysql.pid
user = mysql
bind-address = 0.0.0.0
server-id = 1
skip-name-resolve
# skip-networking

back_log = 600
max_connections = 1000
max_connect_errors = 6000
open_files_limit = 65535

# === 關鍵精簡參數 ===
table_open_cache = 128
performance_schema = 0          # 完全關閉 P_S,省 ~50-80 MB
performance_schema_max_table_instances = 200
table_definition_cache = 200

max_allowed_packet = 4M
binlog_cache_size = 1M
max_heap_table_size = 8M
tmp_table_size = 16M

read_buffer_size = 2M
read_rnd_buffer_size = 8M
sort_buffer_size = 8M
join_buffer_size = 8M
thread_cache_size = 8

query_cache_size = 8M
query_cache_limit = 2M
key_buffer_size = 4M

ft_min_word_len = 4
transaction_isolation = REPEATABLE-READ
log_bin = mysql-bin
binlog_format = mixed
expire_logs_days = 30
log_error = /data/mysql/mysql-error.log
slow_query_log = 1
long_query_time = 1
slow_query_log_file = /data/mysql/mysql-slow.log

explicit_defaults_for_timestamp = true
skip-external-locking
default-storage-engine = InnoDB
innodb_file_per_table = 1
innodb_open_files = 500

# === InnoDB 核心記憶體 ===
innodb_buffer_pool_size = 64M   # 物理記憶體 10-15%,512 MB 機器建議 64-96M
innodb_write_io_threads = 4
innodb_read_io_threads = 4
innodb_thread_concurrency = 0
innodb_purge_threads = 1
innodb_flush_log_at_trx_commit = 2   # 性能優先,允許 1 秒丟失
innodb_log_buffer_size = 2M
innodb_log_file_size = 32M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120

bulk_insert_buffer_size = 8M
myisam_sort_buffer_size = 8M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1

interactive_timeout = 28800
wait_timeout = 28800

[mysqldump]
quick
max_allowed_packet = 16M

[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
read_buffer = 4M
write_buffer = 4M

參數解釋速查表

參數作用調整建議
performance_schema啟用效能監控框架小記憶體建議 0 關閉
table_open_cache表緩存數量併發連接數 × 每連接表數,小機器 128-256
innodb_buffer_pool_sizeInnoDB 數據+索引緩存獨佔 DB 服務器可設 60-80% 物理記憶體;共用機器設 10-15%
innodb_flush_log_at_trx_commit事務提交刷盤策略2:每秒刷盤,效能大增,極端崩潰丟 1 秒
query_cache_size查詢緩存高併發寫入場景建議關閉(0),讀多寫少可保留 8-16M

驗證效果

# 啟動後觀察 RSS
ps aux | grep mysqld
# 預期:RES ~80-120 MB,不再觸發 OOM

總結

小記憶體 VPS 跑 MySQL 5.6 核心策略:關閉 Performance Schema、縮減表緩存、壓縮 Buffer Pool、放寬刷盤策略。上線前務必做壓測,確認無 Table cache full、Out of memory 錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved