You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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连接:

  1. 登录MySQL:mysql -u root -p(密码为空直接回车)
  2. 执行查询查看用户权限:
    SELECT user, host FROM mysql.user WHERE user='root';
    
  3. 如果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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:57:24