Linux 系统安装 MySQL(CentOS8/Ubuntu),命令行实操完整版

📅 2026/7/9 21:07:35 👁️ 阅读次数 📝 编程学习
Linux 系统安装 MySQL(CentOS8/Ubuntu),命令行实操完整版

前言

开发和服务器部署基本都是 Linux 环境,本篇手把手教你CentOS8 和 Ubuntu两大主流系统命令行安装 MySQL,全程命令复制即用,无多余操作。


一、通用前置准备

关闭防火墙、关闭 SELinux(服务器环境可选)

bash

运行

# CentOS systemctl stop firewalld systemctl disable firewalld # Ubuntu ufw allow 3306

二、CentOS8 安装 MySQL

  1. 安装 MySQL 源

bash

运行

dnf install -y https://dev.mysql.com/get/mysql80-community-release-el8-3.noarch.rpm
  1. 安装 MySQL 服务

bash

运行

dnf install -y mysql-community-server
  1. 启动并设置开机自启

bash

运行

systemctl start mysqld systemctl enable mysqld
  1. 查看初始临时密码

bash

运行

grep 'temporary password' /var/log/mysqld.log
  1. 登录修改密码

bash

运行

mysql -uroot -p ALTER USER 'root'@'localhost' IDENTIFIED BY 'Root@123456';
  1. 开启远程连接

sql

CREATE USER 'root'@'%' IDENTIFIED BY 'Root@123456'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;

三、Ubuntu 安装 MySQL

  1. 更新软件源

bash

运行

apt update
  1. 直接安装

bash

运行

apt install mysql-server -y
  1. 启动自启

bash

运行

systemctl start mysql systemctl enable mysql
  1. 进入配置授权远程访问

bash

运行

sudo mysql

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;
  1. 修改配置允许外网连接编辑/etc/mysql/mysql.conf.d/mysqld.cnfbind-address = 127.0.0.1注释掉,重启 MySQL。

四、常用运维命令

bash

运行

# 启动/停止/重启 systemctl start mysqld systemctl stop mysqld systemctl restart mysqld # 查看状态 systemctl status mysqld