前言
开发和服务器部署基本都是 Linux 环境,本篇手把手教你 CentOS8 和 Ubuntu 两大主流系统命令行安装 MySQL,全程命令复制即用,无多余操作。
一、通用前置准备
关闭防火墙、关闭 SELinux(服务器环境可选)
bash
运行
bash
# CentOS
systemctl stop firewalld
systemctl disable firewalld
# Ubuntu
ufw allow 3306
二、CentOS8 安装 MySQL
- 安装 MySQL 源
bash
运行
bash
dnf install -y https://dev.mysql.com/get/mysql80-community-release-el8-3.noarch.rpm
- 安装 MySQL 服务
bash
运行
bash
dnf install -y mysql-community-server
- 启动并设置开机自启
bash
运行
bash
systemctl start mysqld
systemctl enable mysqld
- 查看初始临时密码
bash
运行
bash
grep 'temporary password' /var/log/mysqld.log
- 登录修改密码
bash
运行
bash
mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'Root@123456';
- 开启远程连接
sql
sql
CREATE USER 'root'@'%' IDENTIFIED BY 'Root@123456';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
三、Ubuntu 安装 MySQL
- 更新软件源
bash
运行
bash
apt update
- 直接安装
bash
运行
bash
apt install mysql-server -y
- 启动自启
bash
运行
bash
systemctl start mysql
systemctl enable mysql
- 进入配置授权远程访问
bash
运行
bash
sudo mysql
sql
sql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
CREATE USER 'root'@'%' IDENTIFIED BY '123456';
GRANT ALL ON *.* TO 'root'@'%';
FLUSH PRIVILEGES;
- 修改配置允许外网连接编辑
/etc/mysql/mysql.conf.d/mysqld.cnf把 **bind-address = 127.0.0.1**注释掉,重启 MySQL。
四、常用运维命令
bash
运行
bash
# 启动/停止/重启
systemctl start mysqld
systemctl stop mysqld
systemctl restart mysqld
# 查看状态
systemctl status mysqld