解决Spring Boot 部署到服务器无法连接MySQL 问题

本文记录了在部署Spring Boot项目到Digital Ocean服务器时遇到的无法连接MySQL问题。通过检查application.properties文件、确认数据库配置以及解决MySQL远程访问权限问题,最终成功解决了通信链接失败的错误。建议在允许所有IP访问时注意风险。

今天spring boot 项目终于写好了,打算部署在刚买的digital ocean服务器上,从github pull之后,执行:

mvn clean compile package

报错提示:

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
	at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.18.jar:8.0.18]

第一感觉是数据库连接的问题,先把application.properties里关于databse的内容全部comment:

#spring.datasource.url=jdbc:mysql://***:3306/db_test?serverTimezone=GMT%2B8
#spring.datasource.username=root
#spring.datasource.password=password

再执行:

mvn spring-boot:run

项目果然能跑起来了,说明就是数据库连接问题。

这个问题太艰难了,出现问题的可能的点很多,网上找了N多资料,有同样问题的同学可以看一下汇总:

https://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc-and-mysql

这里面第二高赞提到了mysql localhost以外的权限问题

详细步骤参考了digital ocean 官方的解答:  Hot to Allow Remote Access to MySQL

我个人的问题就是是MySQL没有开启允许外部网访问, 因为mysql默认只允许127.0.0.1访问

/etc/mysql/mysql.conf.d/mysqld.cnf
. . .
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = 127.0.0.1
. . .

把这里的bind-address 改成* 或者0.0.0.0,再执行:

sudo ufw allow from 允许访问的IP地址 to any port 3306

如果你想允许所有ip都可以访问,可以

sudo ufw allow 3306

当然这样风险就太高了,不建议。

最后重启MySQL:

sudo systemctl restart mysql

再启动spring boot project, 终于成功运行了。

 

部署问题很难受,debug了一整天。希望大家部署过程顺利~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值