内容简介:本文风哥教程参考Linux官方文档、Red Hat Enterprise Linux官方文档、Ansible Automation Platform官方文档、Docker官方文档、Kubernetes官方文档和Podman官方文档等内容,详细介绍了相关技术的配置和使用方法。
风哥提示:
本文档详细介绍MySQL数据库服务器的安装、配置和管理方法。
Part01-MySQL安装
1.1 安装MySQL服务
$ sudo dnf install -y mysql-server
Last metadata expiration check: 0:45:23 ago on Thu 03 Apr 2026 23:10:15 AM CST.
Dependencies resolved.
================================================================================
Package Architecture Version Repository Size
================================================================================
Installing:
mysql-server x86_64 8.0.32-1.el9 appstream 11 M
Transaction Summary
================================================================================
Install 1 Package
Total download size: 11 M
Installed size: 55 M
Downloading Packages:
mysql-server-8.0.32-1.el9.x86_64.rpm 11 MB/s | 11 MB 00:01
——————————————————————————–
Total 11 MB/s | 11 MB 00:01
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : mysql-server-8.0.32-1.el9.x86_64 1/1
Running scriptlet: mysql-server-8.0.32-1.el9.x86_64 1/1
Verifying : mysql-server-8.0.32-1.el9.x86_64 1/1
Installed:
mysql-server-8.0.32-1.el9.x86_64
Complete!
# 启动MySQL服务
$ sudo systemctl start mysqld
# 设置开机自启动
$ sudo systemctl enable mysqld
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
# 查看服务状态
$ sudo systemctl status mysqld
● mysqld.service – MySQL 8.0 database server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; preset: disabled)
Active: active (running) since Thu 2026-04-03 23:10:00 CST; 10s ago
Process: 12366 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
Process: 12367 ExecStartPre=/usr/libexec/mysql-prepare-db-dir mysqld.service (code=exited, status=0/SUCCESS)
Main PID: 12438 (mysqld)
Status: “Server is operational”
Tasks: 38 (limit: 49152)
Memory: 350.5M
CPU: 500ms
CGroup: /system.slice/mysqld.service
└─12438 /usr/libexec/mysqld –basedir=/usr
Apr 03 23:10:00 rhel10 systemd[1]: Starting MySQL 8.0 database server…
Apr 03 23:10:00 rhel10 mysql-prepare-db-dir[12367]: Initializing MySQL database
Apr 03 23:10:00 rhel10 systemd[1]: Started MySQL 8.0 database server.
# 查看临时密码
$ sudo grep ‘temporary password’ /var/log/mysqld.log
2026-04-03T15:10:00.123456Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: Abc123!@#
# 安全初始化
$ sudo mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:
The existing password for the user account root has expired. Please set a new password.
New password:
Re-enter new password:
The ‘validate_password’ component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.
Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y
New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
Normally, root should only be allowed to connect from
‘localhost’. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.
By default, MySQL comes with a database named ‘test’ that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
– Dropping test database…
Success.
– Removing privileges on test database…
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
# 配置防火墙
$ sudo firewall-cmd –permanent –add-service=mysql
success
$ sudo firewall-cmd –reload
success
# 测试连接
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.32 Source distribution
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.
mysql> show databases;
+——————–+
| Database |
+——————–+
| information_schema |
| mysql |
| performance_schema |
| sys |
+——————–+
4 rows in set (0.00 sec)
mysql> quit
Bye
Part02-MySQL配置文件
2.1 配置my.cnf
$ sudo cp /etc/my.cnf /etc/my.cnf.bak
# 编辑配置文件
$ sudo tee /etc/my.cnf << EOF
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
# 字符集配置
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
# 网络配置
bind-address=0.0.0.0
port=3306
max_connections=200
# 缓冲区配置
innodb_buffer_pool_size=1G
innodb_log_file_size=256M
innodb_log_buffer_size=16M
# 查询缓存
query_cache_type=0
query_cache_size=0
# 慢查询日志
slow_query_log=1
slow_query_log_file=/var/log/mysql-slow.log
long_query_time=2
# 二进制日志
log-bin=mysql-bin
server-id=1
binlog_format=ROW
expire_logs_days=7
# 安全配置
skip-name-resolve
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
[client]
default-character-set=utf8mb4
socket=/var/lib/mysql/mysql.sock
[mysql]
default-character-set=utf8mb4
EOF
# 重启服务
$ sudo systemctl restart mysqld
# 验证配置
$ mysql -u root -p -e "SHOW VARIABLES LIKE 'character_set%';"
Enter password:
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
Part03-用户和权限管理
3.1 创建用户和授权
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.
# 创建数据库
mysql> CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Query OK, 1 row affected (0.01 sec)
# 创建用户
mysql> CREATE USER ‘myuser’@’localhost’ 更多学习教程公众号风哥教程itpux_comIDENTIFIED BY ‘MyPassword123!’;
Query OK, 0 rows affected (0.02 sec)
mysql> CREATE USER ‘myuser’@’%’ IDENTIFIED BY ‘MyPassword123!’;
Query OK, 0 rows affected (0.01 sec)
# 授予权限
mysql> GRANT ALL PRIVILEGES ON mydb.* TO ‘myuser’@’localhost’;
Query OK, 0 rows affected (0.01 sec)
mysql> GRANT ALL PRIVILEGES ON mydb.* TO ‘myuser’@’%’;
Query OK, 0 rows affected (0.01 sec)
# 刷新权限
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
# 查看用户权限
mysql> SHOW GRANTS FOR ‘myuser’@’localhost’;
+——————————————————–+
| Grants for myuser@localhost |
+——————————————————–+
| GRANT USAGE ON *.* TO `myuser`@`localhost` |
| GRANT ALL PRIVILEGES ON `mydb`.* TO `myuser`@`localhost` |
+——————————————————–+
2 rows in set (0.00 sec)
# 撤销权限
mysql> REVOKE ALL PRIVILEGES ON mydb.* FROM ‘myuser’@’localhost’;
Query OK, 0 rows affected (0.01 sec)
# 删除用户
mysql> DROP USER ‘myuser’@’localhost’;
Query OK, 0 rows affected (0.01 sec)
# 修改用户密码
mysql> ALTER USER ‘myuser’@’%’ IDENTIFIED BY ‘NewPassword456!’;
Query OK, 0 rows affected (0.01 sec)
# 查看所有用户
mysql> SELECT User, Host FROM mysql.user;
+——————+———–+
| User | Host |
+——————+———–+
| myuser | % |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+——————+———–+
5 rows in set (0.00 sec)
mysql> quit
Bye
Part04-数据库备份与恢复
4.1 备份和恢复数据库
$ sudo mysqldump -u root -p –all-databases > /backup/all_databases.sql
Enter password:
# 备份单个数据库
$ sudo mysqldump -u root -p mydb > /backup/mydb.sql
Enter password:
# 备份多个数据库
$ sudo mysqldump -u root -p –databases mydb testdb > /backup/multi_databases.sql
Enter password:
# 备份表结构
$ sudo mysqldump -u root -p –no-data mydb > /backup/mydb_structure.sql
Enter password:
# 备份数据
$ sudo mysqldump -u root -p –no-create-info mydb > /backup/mydb_data.sql
Enter password:
# 恢复数据库
$ sudo mysql -u root -p mydb < /backup/mydb.sql
Enter password:
# 恢复所有数据库
$ sudo mysql -u root -p < /backup/all_databases.sql
Enter password:
# 自动备份脚本
$ cat > /usr/local/bin/mysql-backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/backup/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
MYSQL_USER="root"
MYSQL_PASSWORD="YourPassword"
DATABASES=$(mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)")
mkdir -p $BACKUP_DIR
for db in $DATABASES; do
mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $db | gzip > $BACKUP_DIR/$db-$DATE.sql.gz
done
find $BACKUP_DIR -name “*.sql.gz” -mtime +7 -delete
echo “Backup completed at $(date)”
EOF
chmod +x /usr/local/bin/mysql-backup.sh
# 配置定时备份
$ sudo tee /etc/cron.d/mysql-backup << EOF
0 2 * * * root /usr/local/bin/mysql-backup.sh >> /var/log/mysql-backup.log 2>&1
EOF
Part05-MySQL性能优化
5.1 性能优化配置
$ mysql -u root -p -e “SHOW STATUS LIKE ‘Threads%’;”
Enter password:
+——————-+——-+
| Variable_name | Value |
+——————-+——-+
| Threads_cached | 0 |
| Threads_connected | 1 |
| Threads_created | 1 |
| Threads_running | 1 |
+——————-+——-+
# 查看MySQL变量
$ mysql -u root -p -e “SHOW VARIABLES LIKE ‘max_connections’;”
Enter password:
+—————–+——-+
| Variable_name | Value |
+—————–+——-+
| max_connections | 200 |
+—————–+——-+
# 优化配置
$ sudo tee -a /etc/my.cnf << EOF
# 连接优化
max_connections=500
max_connect_errors=1000
wait_timeout=600
interactive_timeout=600
# InnoDB优化
innodb_buffer_pool_size=2G
innodb_buffer_pool_instances=4
innodb_log_file_size=512M
innodb_log_buffer_size=32M
innodb_flush_log_at_trx_commit=2
innodb_flush_method=O_DIRECT
innodb_file_per_table=1
# 查询优化
join_buffer_size=4M
sort_buffer_size=4M
read_buffer_size=4M
read_rnd_buffer_size=8M
table_open_cache=2000
thread_cache_size=100
# 临时表优化
tmp_table_size=64M
max_heap_table_size=64M
EOF
# 重启服务
$ sudo systemctl restart mysqld
# 查看慢查询
$ mysql -u root -p -e "SELECT * FROM mysql.slow_log LIMIT 10;"
Enter password:
Empty set (0.00 sec)
# 分析表
$ mysql -u root -p -学习交流加群风哥微信: itpux-come "ANALYZE TABLE mydb.users;"
Enter password:
+------------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+------------+---------+----------+----------+
| mydb.users | analyze | status | OK |
+------------+---------+----------+----------+
# 优化表
$ mysql -u root -p -e "OPTIMIZE TABLE mydb.users;"
Enter password:
+------------+----------+----------+-------------------------------------------------------------------+
| Table | Op | Msg_type | Msg_text |
+------------+----------+----------+-------------------------------------------------------------------+
| mydb.users | optimize | note | Table does not support optimize, doing recreate + analyze instead |
| mydb.users | optimize | status | OK |
+------------+----------+----------+-------------------------------------------------------------------+
1. 设置强密码保护root账户
2. 配置合理的缓冲区大小
3. 启用慢查询日志分析性能
4. 定期备份数据库
5. 监控数据库性能指标
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
