CentOS 7 基礎倉庫不再包含 mysql-server(改為 MariaDB),需配置 MySQL 官方 YUM Repository 安裝社區版。本文詳細記錄 5.6/5.7 版本源配置、GPG Key 失效解決、安裝驗證全流程。
| 項目 | CentOS 6 | CentOS 7 |
|---|---|---|
| 預設數據庫 | MySQL 5.1/5.5 | MariaDB 5.5 (兼容 MySQL) |
| 包名 | mysql-server | mysql-community-server |
| 服務名 | mysqld | mysqld (systemd 管理) |
| 官方源支持 | EL 6 | EL 7 |
路徑:/etc/yum.repos.d/mysql-community.repo
# MySQL 5.6 Community Server
[mysql56-community]
name=MySQL 5.6 Community Server
baseurl=https://repo.mysql.com/yum/mysql-5.6-community/el/7/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
# MySQL 5.7 Community Server (Development Milestone Release)
[mysql57-community-dmr]
name=MySQL 5.7 Community Server Development Milestone Release
baseurl=https://repo.mysql.com/yum/mysql-5.7-community/el/7/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
注意: 5.7 GA 版源路徑為 mysql-5.7-community/el/7/,dmr 為早期開發版標識,生產環境請使用 GA 源。
報錯現象:
GPG key retrieval failed: [Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql"
原因: 本地缺少 MySQL 官方簽名公鑰文件。
方案 A:手動導入公鑰(推薦,保持 gpgcheck=1 安全)
# 從官方下載或從已安裝 MySQL 的系統複製
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
# 或
wget -O /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
方案 B:暫時關閉 GPG 校驗(快速測試用,生產不建議)
# 修改 repo 文件
gpgcheck=0
# 清理緩存並安裝
yum clean all
yum makecache
yum install mysql-community-server
依賴會自動拉取:mysql-community-client、mysql-community-common、mysql-community-libs 等。
# systemd 管理
systemctl start mysqld
systemctl enable mysqld
systemctl status mysqld
# 5.7+ 生成臨時 root 密碼於日志
grep 'temporary password' /var/log/mysqld.log
# 2023-01-01T00:00:00.000000Z 1 [Note] A temporary password is generated for root@localhost: xYz#Abc123
# 安全初始化(修改密碼、清理匿名用戶、禁止 root 遠程、移除 test 庫)
mysql_secure_installation
mysql -u root -p
# 輸入新設置的密碼
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.6.51 |
+-----------+
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
| 問題 | 解決 |
|---|---|
yum 安裝報 Nothing to do / 版本不對 | 檢查 baseurl 中 $basearch 變量是否正確解析為 x86_64;清理緩存 yum clean all 重試 |
啟動失敗 Job for mysqld.service failed | 查看 journalctl -u mysqld -xe 或 /var/log/mysqld.log;常見:datadir 權限、my.cnf 語法錯、端口佔用、SELinux |
| 無法遠程連接 | 1. 創建遠程用戶 CREATE USER 'user'@'%' IDENTIFIED BY 'pass';2. 防火牆放行 firewall-cmd --permanent --add-port=3306/tcp && firewall-cmd --reload3. 檢查 bind-address=0.0.0.0 (my.cnf) |
| 字符集亂碼 | 配置 [mysqld] character-set-server=utf8mb4,重建庫表 |
| MariaDB 衝突 | CentOS 7 預裝 mariadb-libs,安裝 MySQL 會自動替換為 mysql-community-libs-compat 兼容包,一般無需手動移除 |
CentOS 7 安裝 MySQL 官方版關鍵在:配置正確的 EL7 版本源 → 導入 GPG Key 保持安全校驗 → yum install mysql-community-server → systemd 管理服務 → mysql_secure_installation 落地安全基線。掌握此標準流程,可在任意 RHEL 7 系發行版(CentOS、RHEL、Oracle Linux、Rocky、AlmaLinux)上穩健部署 MySQL 5.6/5.7/8.0 生產實例。