針對 Linux(CentOS/Ubuntu)環境,使用官方 Generic Linux Glibc 二進制包安裝 MySQL 5.6.20,涵蓋使用者建立、目錄規劃、my.cnf 核心參數、systemd 服務註冊、字符集統一為 utf8mb4、root 密碼修改與 mysql_secure_installation 加固。
groupadd mysql
useradd -r -g mysql -s /sbin/nologin mysql
mkdir -p /data/mysql/{data,logs,tmp}
chown -R mysql:mysql /data/mysql
tar -xzf mysql-5.6.20-linux-glibc2.5-x86_64.tar.gz -C /usr/local/ ln -s /usr/local/mysql-5.6.20-linux-glibc2.5-x86_64 /usr/local/mysql
[mysqld] basedir=/usr/local/mysql datadir=/data/mysql/data socket=/tmp/mysql.sock port=3306 character-set-server=utf8mb4 collation-server=utf8mb4_general_ci explicit_defaults_for_timestamp=true sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION innodb_buffer_pool_size=1G innodb_log_file_size=256M innodb_flush_log_at_trx_commit=1 sync_binlog=1 max_connections=500 log-error=/data/mysql/logs/error.log slow_query_log=1 slow_query_log_file=/data/mysql/logs/slow.log long_query_time=1 log_queries_not_using_indexes=1 server-id=1 log-bin=/data/mysql/logs/binlog binlog_format=ROW expire_logs_days=7 gtid_mode=ON enforce_gtid_consistency=ON [client] default-character-set=utf8mb4 socket=/tmp/mysql.sock [mysql] default-character-set=utf8mb4
cd /usr/local/mysql ./scripts/mysql_install_db --user=mysql --datadir=/data/mysql/data --basedir=/usr/local/mysql
cp support-files/mysql.server /etc/init.d/mysqld chmod +x /etc/init.d/mysqld chkconfig --add mysqld chkconfig mysqld on # 或 systemd cat > /etc/systemd/system/mysqld.service <<'EOF' [Unit] Description=MySQL Server After=network.target [Service] Type=forking User=mysql Group=mysql ExecStart=/etc/init.d/mysqld start ExecStop=/etc/init.d/mysqld stop PIDFile=/data/mysql/data/mysqld.pid [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable mysqld
systemctl start mysqld # 修改 root 密碼 /usr/local/mysql/bin/mysqladmin -u root -h $(hostname) password 'StrongPass@2024' # 或執行安全向導 /usr/local/mysql/bin/mysql_secure_installation
mysql -uroot -p -e "SHOW VARIABLES LIKE '%character%'; SHOW VARIABLES LIKE '%gtid%';" # 確認 character_set_server=utf8mb4, gtid_mode=ON
explicit_defaults_for_timestamp=true 避免 5.6+ 警告。innodb_log_file_size 修改需先停庫、刪除舊 ib_logfile* 再啟動。mysqld_safe 於 /usr/libexec,直接用 systemd 管理。