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

今天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了一整天。希望大家部署过程顺利~


版权声明:本文为bigbroase原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。