Ubuntu 22.04环境下Spring项目无法连接MySQL数据库
问题:Spring项目连接Ubuntu上的MySQL报通信链路失败
环境信息
- 系统:Ubuntu 22.04
- MySQL版本:
mysql Ver 8.0.35-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu)) - Spring项目,已核对数据库凭证
项目配置文件(application.properties)
# Database configuration spring.datasource.url=jdbc:mysql://localhost:3306/stocky spring.datasource.username=root spring.datasource.password= # Hibernate configuration spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update # Server configuration server.port=8090 # Logging configuration logging.level.org.springframework=INFO logging.level.com.example=DEBUG
报错信息
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: 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.
已排查:MySQL服务正常运行,3306端口可用
解决方案尝试
1. 调整MySQL的TCP连接配置
Ubuntu上的MySQL 8.0默认可能限制TCP/IP连接,仅允许socket连接。修改MySQL配置文件/etc/mysql/mysql.conf.d/mysqld.cnf:
- 找到
bind-address配置项,改为0.0.0.0(允许所有IP连接)或直接注释掉 - 重启MySQL服务:
sudo systemctl restart mysql
2. 检查并更新root用户的连接权限
确保root用户允许从localhost通过TCP连接:
- 登录MySQL:
mysql -u root -p(密码为空直接回车) - 执行查询查看用户权限:
SELECT user, host FROM mysql.user WHERE user='root'; - 如果root用户的host不是
localhost或%,执行以下命令更新权限:ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ''; FLUSH PRIVILEGES;
3. 补充JDBC URL的必要参数
MySQL 8.0需要指定时区、SSL等参数,修改数据源URL为:
spring.datasource.url=jdbc:mysql://localhost:3306/stocky?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
4. 确认MySQL驱动版本适配
Spring项目中需使用适配MySQL 8.0的驱动,在pom.xml中添加或更新依赖:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.35</version> </dependency>
内容的提问来源于stack exchange,提问作者youssef ACHCHIRAJ
相关产品推荐
相关产品推荐

