在云服务器上手动安装 MySQL 数据库的步骤因操作系统不同而略有差异。以下以 Ubuntu 20.04/22.04 和 CentOS 7/8 / Rocky Linux 8+ 为例,详细介绍手动安装 MySQL 的过程。
✅ 一、准备工作
-
登录云服务器
使用 SSH 登录你的云服务器:ssh username@your_server_ip -
更新系统包(推荐)
# Ubuntu/Debian sudo apt update && sudo apt upgrade -y # CentOS/Rocky Linux sudo yum update -y # CentOS 7/8 sudo dnf update -y # Rocky Linux 8+
✅ 二、在 Ubuntu 上安装 MySQL
步骤 1:安装 MySQL 服务器
sudo apt install mysql-server -y
这会安装最新版本的 MySQL(通常是 8.0)
步骤 2:启动并设置开机自启
sudo systemctl start mysql
sudo systemctl enable mysql
步骤 3:运行安全配置脚本(推荐)
sudo mysql_secure_installation
该脚本会引导你:
- 设置 root 密码
- 删除匿名用户
- 禁止 root 远程登录
- 删除测试数据库
- 重新加载权限表
按提示操作即可。
步骤 4:登录 MySQL 验证
sudo mysql -u root -p
输入密码后进入 MySQL 命令行即表示安装成功。
✅ 三、在 CentOS / Rocky Linux 上安装 MySQL
步骤 1:添加 MySQL 官方 Yum 源
MySQL 不在默认源中,需手动添加官方仓库:
# 下载并安装 MySQL Yum 源
wget https://dev.mysql.com/get/mysql80-community-release-el$(rpm -E %{rhel})-1.noarch.rpm
sudo rpm -ivh mysql80-community-release-el$(rpm -E %{rhel})-1.noarch.rpm
注:此命令自动识别系统版本(如 el7 或 el8)
步骤 2:安装 MySQL 服务器
sudo yum install mysql-server -y # CentOS 7/8
sudo dnf install mysql-server -y # Rocky Linux 8+
步骤 3:启动并启用服务
sudo systemctl start mysqld
sudo systemctl enable mysqld
步骤 4:获取临时 root 密码(仅首次启动)
查看临时生成的 root 密码:
sudo grep 'temporary password' /var/log/mysqld.log
输出示例:
A temporary password is generated for root@localhost: abc123XYZ!
步骤 5:运行安全初始化
sudo mysql_secure_installation
系统会提示你输入当前 root 密码(用上一步查到的),然后设置新密码并完成安全配置。
✅ 四、基本配置(可选但建议)
1. 允许远程连接(如需从外部访问)
编辑 MySQL 配置文件:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf # Ubuntu
sudo nano /etc/my.cnf # CentOS/Rocky
找到 bind-address 行,修改为:
bind-address = 0.0.0.0
或注释掉该行(默认绑定 127.0.0.1,禁止远程访问)。
2. 在 MySQL 中授权远程用户
登录 MySQL:
mysql -u root -p
执行:
CREATE USER 'admin'@'%' IDENTIFIED BY 'YourStrongPassword';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
注意:开放
%权限存在安全风险,请确保防火墙限制访问 IP。
3. 重启 MySQL 服务
sudo systemctl restart mysql # Ubuntu
sudo systemctl restart mysqld # CentOS/Rocky
✅ 五、配置云服务器安全组/防火墙
确保云服务商(阿里云、腾讯云、AWS等)的安全组放行 3306 端口。
同时在服务器本地开启防火墙端口:
Ubuntu(使用 ufw)
sudo ufw allow 3306/tcp
CentOS/Rocky(使用 firewalld)
sudo firewall-cmd --permanent --add-port=3306/tcp
sudo firewall-cmd --reload
✅ 六、验证安装
mysql --version
或登录后查看状态:
STATUS;
🛡️ 安全建议
- 不要长期使用 root 账户远程连接。
- 定期备份数据库。
- 使用强密码策略。
- 限制远程访问 IP 范围。
- 及时更新 MySQL 版本。
如有特定需求(如安装 MySQL 5.7、主从复制、Docker 安装等),可进一步说明,我会提供详细方案。
CLOUD云枢