mysql8 允许外网连接mysql

在MySQL 8中允许外网连接,你需要完成以下几个关键步骤:

1. 修改MySQL用户权限:

确保数据库用户拥有远程访问的权限。例如,创建一个新用户或修改现有用户的权限,允许从任意IP地址进行连接:

#第一种方法
#连上mysql
CREATE USER 'your_user'@'%' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON *.* TO 'your_user'@'%';
FLUSH PRIVILEGES;

#第二种方法

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed

mysql> update user set host='%' where user='root';    更改主机
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> flush privileges;    //刷新
Query OK, 0 rows affected (0.00 sec)

mysql> grant select on test.* to root;  //授权成功
Query OK, 0 rows affected (0.00 sec)


如果已有用户需要更新权限,则可以只运行第二条命令。

2. 配置MySQL服务监听所有网络接口:

检查MySQL配置文件(通常是 /etc/mysql/my.cnf/etc/my.cnf或 /etc/mysql/mysql.conf.d/mysqld.cnf),确认 bind-address 设置正确:

[mysqld]
...
bind-address = 0.0.0.0
...

这会使得MySQL服务器监听所有网络接口,包括来自公网的请求。

3. 开启防火墙端口:

对于Linux服务器上的防火墙,比如使用iptables,允许外部通过3306端口连接到MySQL:

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
sudo iptables-save # (持久化iptables规则)
# 如果你使用的是firewalld防火墙
sudo firewall-cmd --permanent --add-port=3306/tcp
sudo firewall-cmd --reload

如果是云服务器环境如AWS、Azure等,还需要在控制台的安全组设置中为实例添加一条入站规则,开放3306端口。

4. 安全考虑:

允许外网连接MySQL可能会增加安全风险。强烈建议仅对特定IP范围开放访问,并启用SSL加密以保护数据传输安全。另外,定期审计和更新密码策略也很重要。

5. 重启MySQL服务:

应用以上更改后,请重启MySQL服务以使配置生效:

sudo systemctl restart mysql
#或者
sudo service mysqld restart

6. 远程连接报错:

在这里插入图片描述
用root 连接不上,可以新建一个用户,用新用户连接。


mysql> select host,user,plugin from user;
+-----------+------------------+-----------------------+
| host      | user             | plugin                |
+-----------+------------------+-----------------------+
| %         | root             | auth_socket           |
| %         | tusi             | mysql_native_password |
| localhost | debian-sys-maint | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session    | caching_sha2_password |
| localhost | mysql.sys        | caching_sha2_password |
+-----------+------------------+-----------------------+
6 rows in set (0.00 sec)


#修改root的连接方式
mysql> CREATE USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
#赋权
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;


完成这些步骤后,你的MySQL 8数据库应该可以从外网进行连接了。但请注意,生产环境中务必采取严格的安全措施来防止未授权访问。

  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值