本地Spring Boot连接远程MySQL报错:Host不允许访问
问题解决:Spring Boot连接远程MySQL的Host授权与SSH隧道配置
一、解决Host不允许连接的错误
你遇到的Host 'x.x.x.x' is not allowed to connect to this MySQL server错误,本质是MySQL用户权限限制:
- MySQL Workbench通过SSH连接时,MySQL接收到的请求来源是服务器本地的
127.0.0.1,所以只要用户授权了localhost或127.0.0.1就能访问; - 直接用Spring Boot连接(未走SSH)时,请求来源是你的本地公网IP
x.x.x.x,该IP未被MySQL用户授权。
修复步骤:
- 通过SSH登录远程Ubuntu服务器,进入MySQL命令行:
mysql -u root -p - 查询当前MySQL用户的授权主机:
SELECT user, host FROM mysql.user; - 给你的数据库用户授权本地IP访问(替换占位符):
如果需要允许所有IP访问(测试环境可用,生产不建议),把GRANT ALL PRIVILEGES ON 你的数据库名.* TO '你的MySQL用户名'@'x.x.x.x' IDENTIFIED BY '你的MySQL密码';x.x.x.x换成%:GRANT ALL PRIVILEGES ON 你的数据库名.* TO '你的MySQL用户名'@'%' IDENTIFIED BY '你的MySQL密码'; - 刷新权限使配置生效:
FLUSH PRIVILEGES;
二、Spring Boot中配置SSH隧道(模拟Workbench的连接方式)
Workbench的Standard TCP/IP over SSH本质是建立SSH隧道,将远程MySQL端口映射到本地端口。Spring Boot实现这个有两种方式:
方式1:手动建立SSH隧道(快速简单)
在本地终端执行以下命令,将本地3306端口映射到远程服务器的3306端口:
ssh -L 3306:127.0.0.1:3306 服务器SSH用户名@服务器公网IP
保持终端窗口打开,然后Spring Boot的数据库配置(application.yml或application.properties)指向本地映射的端口:
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/你的数据库名?useSSL=false&serverTimezone=UTC username: 你的MySQL用户名 password: 你的MySQL密码 driver-class-name: com.mysql.cj.jdbc.Driver
方式2:代码集成SSH隧道(自动建立)
通过jsch库在Spring Boot启动时自动建立SSH隧道,无需手动执行命令:
- 先在pom.xml添加依赖:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> - 编写SSH隧道配置类:
import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.PreDestroy; import java.util.Properties; @Configuration public class SshTunnelConfig { private Session sshSession; @Bean public Session initSshTunnel() throws JSchException { JSch jsch = new JSch(); // 初始化SSH会话(替换为你的服务器SSH信息) sshSession = jsch.getSession("服务器SSH用户名", "服务器公网IP", 22); sshSession.setPassword("服务器SSH密码"); // 跳过主机密钥验证(生产环境建议使用密钥登录,替换为jsch.addIdentity("密钥文件路径")) Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); sshSession.setConfig(config); sshSession.connect(); // 将本地3307端口映射到远程MySQL的3306端口 int localPort = sshSession.setPortForwardingL(3307, "127.0.0.1", 3306); System.out.println("SSH隧道已建立,本地映射端口:" + localPort); return sshSession; } @PreDestroy public void closeSshTunnel() { if (sshSession != null && sshSession.isConnected()) { sshSession.disconnect(); System.out.println("SSH隧道已关闭"); } } } - 修改Spring Boot数据库配置,指向本地映射的3307端口:
spring: datasource: url: jdbc:mysql://127.0.0.1:3307/你的数据库名?useSSL=false&serverTimezone=UTC username: 你的MySQL用户名 password: 你的MySQL密码 driver-class-name: com.mysql.cj.jdbc.Driver
内容的提问来源于stack exchange,提问作者ayada
相关产品推荐
相关产品推荐

