在云服务器上手动安装 MySQL 数据库的步骤因操作系统而异。以下以 Ubuntu/Debian 和 CentOS/RHEL 两种主流 Linux 发行版为例,详细介绍手动安装 MySQL 的过程。
✅ 一、准备工作
-
登录云服务器
使用 SSH 登录你的云服务器:ssh username@your_server_ip -
更新系统包
- Ubuntu/Debian:
sudo apt update && sudo apt upgrade -y - CentOS/RHEL:
sudo yum update -y # 或者对于 CentOS 8+/RHEL 8+ 使用 dnf sudo dnf update -y
- Ubuntu/Debian:
✅ 二、在 Ubuntu/Debian 上安装 MySQL
1. 安装 MySQL 服务器
sudo apt install mysql-server -y
2. 启动并启用开机自启
sudo systemctl start mysql
sudo systemctl enable mysql
3. 运行安全配置向导(推荐)
sudo mysql_secure_installation
该脚本会引导你设置:
- root 用户密码
- 移除匿名用户
- 禁止 root 远程登录
- 删除测试数据库
- 重新加载权限表
⚠️ 注意:MySQL 8.0+ 默认使用
caching_sha2_password插件,某些客户端可能不兼容。如需兼容旧客户端,可考虑修改为mysql_native_password。
✅ 三、在 CentOS/RHEL 上安装 MySQL
MySQL 不在默认仓库中,建议使用官方 Yum 仓库。
1. 添加 MySQL Yum 仓库
访问 https://dev.mysql.com/downloads/repo/yum/ 获取最新 RPM 包地址,例如:
wget https://dev.mysql.com/get/mysql80-community-release-el7-7.noarch.rpm
sudo rpm -ivh mysql80-community-release-el7-7.noarch.rpm
替换为你系统的版本(el7、el8、el9)
2. 安装 MySQL 服务器
sudo yum install mysql-server -y
# 或使用 dnf(新版)
sudo dnf install mysql-server -y
3. 启动并启用服务
sudo systemctl start mysqld
sudo systemctl enable mysqld
4. 获取临时 root 密码(仅首次启动)
MySQL 第一次启动时会生成一个临时 root 密码:
sudo grep 'temporary password' /var/log/mysqld.log
5. 运行安全配置
sudo mysql_secure_installation
输入临时密码后,按提示设置新密码并完成安全配置。
✅ 四、基本配置与远程访问(可选)
1. 允许远程连接(谨慎操作)
编辑 MySQL 配置文件:
- Ubuntu:
/etc/mysql/mysql.conf.d/mysqld.cnf - CentOS:
/etc/my.cnf或/etc/my.cnf.d/mysql-server.cnf
找到 bind-address 行,修改为:
bind-address = 0.0.0.0
⚠️ 开放远程访问前请确保防火墙和云平台安全组已配置,并使用强密码。
2. 创建远程访问用户
登录 MySQL:
sudo mysql -u root -p
执行 SQL:
CREATE USER 'remote_user'@'%' IDENTIFIED BY 'StrongPassword123!';
GRANT ALL PRIVILEGES ON *.* TO 'remote_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
3. 防火墙放行端口
-
开放 3306 端口:
- Ubuntu (UFW):
sudo ufw allow 3306/tcp - CentOS (firewalld):
sudo firewall-cmd --permanent --add-port=3306/tcp sudo firewall-cmd --reload
- Ubuntu (UFW):
-
同时在云平台控制台配置安全组规则,允许来源 IP 访问 3306 端口。
✅ 五、验证安装
sudo systemctl status mysql # 或 mysqld
mysql --version
登录测试:
mysql -u root -p
✅ 六、常见问题
| 问题 | 解决方法 |
|---|---|
| 无法启动 MySQL | 查看日志:sudo tail /var/log/mysql/error.log 或 /var/log/mysqld.log |
| 连接被拒绝 | 检查 bind-address、防火墙、安全组 |
| 密码错误 | 使用 ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password'; 重置 |
✅ 总结
| 步骤 | 操作 |
|---|---|
| 1 | 更新系统 |
| 2 | 安装 MySQL 服务 |
| 3 | 启动并启用服务 |
| 4 | 运行 mysql_secure_installation |
| 5 | (可选)配置远程访问 |
| 6 | 配置防火墙和安全组 |
🔐 安全提示:生产环境建议使用专用数据库用户,避免使用 root 远程连接,定期备份数据。
如果你提供具体的操作系统版本(如 Ubuntu 22.04、CentOS 7 等),我可以给出更精确的命令。
云计算导航