Spring Boot,Java,Docker Compose,尝试在两个容器(mysql,my-api)之间建立连接时出现“连接被拒绝”

Posted

技术标签:

【中文标题】Spring Boot,Java,Docker Compose,尝试在两个容器(mysql,my-api)之间建立连接时出现“连接被拒绝”【英文标题】:Spring Boot, Java, Docker Compose, Getting 'Connection refused' while trying to make connection between two container (mysql, my-api) 【发布时间】:2021-09-06 14:31:33 【问题描述】:

当我执行docker-compose up command时,会产生如下错误:

Caused by: java.net.ConnectException: Connection refused

我正在尝试使用 docker-compose 在 mysql 和 My-API 容器这两个容器之间建立连接,但不知何故无法连接。这是 docker-compose.yml:

version: '3'

services:

  discovery-mysql:
    image: mysql:5.7.34
    container_name: discovery-mysql
    environment:
      - MYSQL_ROOT_PASSWORD=tomo
      - MYSQL_DATABASE=r2dbc
    ports:
      - 3307:3306
    networks:
      - common-network

  flyway:
    image: flyway/flyway
    command:
      - url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
    volumes:
      - ./src/main/resources/db/migration:/flyway/sql
      - ./flyway/conf/flyway.config:/flyway.config
    depends_on:
      - discovery-mysql
    networks:
      - common-network

  discovery-app:
    image: tomojava3284/helloworldapi:latest
    restart: on-failure
    depends_on:
      - discovery-mysql
    ports:
      - 8001:8080
    environment:
      - spring.datasource.url=r2dbc:mysql://root:tomo@discovery-mysql:3306/r2dbc
    networks:
      - common-network

networks:
  common-network:
    driver: bridge

我尝试过的事情:

我添加了网络:-common-network 以放入同一个网络,但没有用。我认为 URL r2dbc:mysql://root:tomo@discovery-mysql:3306/r2dbc 没有任何问题。 顺便说一句,当我在 IDE 上本地运行程序时(不使用 docker-compose up),给定 url=r2dbc:mysql://root:tomo@127.0.0.1:3306/r2dbc,它工作正常。

我在堆栈溢出方面看到过类似的线程,但他们的许多解决方案都不起作用(我在“我尝试过的事情”部分中指定了)。

导致错误Caused by: java.net.ConnectException: Connection refused的原因可能是什么?

这里是错误的完整细节:

C:\Users\me\github\HelloWorld>docker-compose up
WARNING: Found orphan containers (mysql) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Starting discovery-mysql ... done
Starting helloworld_flyway_1        ... done
Starting helloworld_discovery-app_1 ... done
Attaching to discovery-mysql, helloworld_flyway_1, helloworld_discovery-app_1
discovery-mysql    | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.34-1debian10 started.
discovery-mysql    | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
discovery-mysql    | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.34-1debian10 started.
discovery-mysql    | 2021-06-23T16:03:23.899462Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).

discovery-mysql    | 2021-06-23T16:03:23.900841Z 0 [Note] mysqld (mysqld 5.7.34) starting as process 1 ...
discovery-mysql    | 2021-06-23T16:03:23.903779Z 0 [Note] InnoDB: PUNCH HOLE support available
discovery-mysql    | 2021-06-23T16:03:23.903816Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
discovery-mysql    | 2021-06-23T16:03:23.903821Z 0 [Note] InnoDB: Uses event mutexes
discovery-mysql    | 2021-06-23T16:03:23.903824Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
discovery-mysql    | 2021-06-23T16:03:23.903827Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
discovery-mysql    | 2021-06-23T16:03:23.903829Z 0 [Note] InnoDB: Using Linux native AIO
discovery-mysql    | 2021-06-23T16:03:23.904263Z 0 [Note] InnoDB: Number of pools: 1
discovery-mysql    | 2021-06-23T16:03:23.904371Z 0 [Note] InnoDB: Using CPU crc32 instructions
discovery-mysql    | 2021-06-23T16:03:23.905996Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
discovery-mysql    | 2021-06-23T16:03:23.914593Z 0 [Note] InnoDB: Completed initialization of buffer pool
discovery-mysql    | 2021-06-23T16:03:23.916694Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
discovery-mysql    | 2021-06-23T16:03:23.928540Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
discovery-mysql    | 2021-06-23T16:03:23.947396Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
discovery-mysql    | 2021-06-23T16:03:23.947471Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
discovery-mysql    | 2021-06-23T16:03:23.978325Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
discovery-mysql    | 2021-06-23T16:03:23.978805Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
discovery-mysql    | 2021-06-23T16:03:23.978846Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
discovery-mysql    | 2021-06-23T16:03:23.979683Z 0 [Note] InnoDB: 5.7.34 started; log sequence number 12664810
discovery-mysql    | 2021-06-23T16:03:23.979948Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
discovery-mysql    | 2021-06-23T16:03:23.980060Z 0 [Note] Plugin 'FEDERATED' is disabled.
discovery-mysql    | 2021-06-23T16:03:23.982100Z 0 [Note] InnoDB: Buffer pool(s) load completed at 210623 16:03:23
discovery-mysql    | 2021-06-23T16:03:23.984495Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
discovery-mysql    | 2021-06-23T16:03:23.984525Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
discovery-mysql    | 2021-06-23T16:03:23.985024Z 0 [Warning] CA certificate ca.pem is self signed.
discovery-mysql    | 2021-06-23T16:03:23.985071Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
discovery-mysql    | 2021-06-23T16:03:23.985582Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
discovery-mysql    | 2021-06-23T16:03:23.985650Z 0 [Note] IPv6 is available.
discovery-mysql    | 2021-06-23T16:03:23.985661Z 0 [Note]   - '::' resolves to '::';
discovery-mysql    | 2021-06-23T16:03:23.985676Z 0 [Note] Server socket created on IP: '::'.
discovery-mysql    | 2021-06-23T16:03:23.992611Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.

discovery-mysql    | 2021-06-23T16:03:23.999904Z 0 [Note] Event Scheduler: Loaded 0 events
discovery-mysql    | 2021-06-23T16:03:24.000165Z 0 [Note] mysqld: ready for connections.
discovery-mysql    | Version: '5.7.34'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
flyway_1           | ERROR: Invalid argument: url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
helloworld_flyway_1 exited with code 1
discovery-app_1    | 
discovery-app_1    |   .   ____          _            __ _ _
discovery-app_1    |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
discovery-app_1    | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
discovery-app_1    |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
discovery-app_1    |   '  |____| .__|_| |_|_| |_\__, | / / / /
discovery-app_1    |  =========|_|==============|___/=/_/_/_/
discovery-app_1    |  :: Spring Boot ::                (v2.5.0)
discovery-app_1    |
discovery-app_1    | 2021-06-23 16:03:25.501  INFO 1 --- [           main] c.t.HelloWorld.HelloWorldApplication     : Starting HelloWorldApplication v0.0.1-SNAPSHOT using Java 16.0.1 on 1d485fdb3de3 with PID 1
(/app.jar started by root in /)
discovery-app_1    | 2021-06-23 16:03:25.503  INFO 1 --- [           main] c.t.HelloWorld.HelloWorldApplication     : No active profile set, falling back to default profiles: default
discovery-app_1    | 2021-06-23 16:03:26.119  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data R2DBC repositories in DEFAULT mode.
discovery-app_1    | 2021-06-23 16:03:26.242  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 118 ms. Found 1 R2DBC repository interfaces.
discovery-app_1    | ****************************************************************************************************************
discovery-app_1    | r2dbc:mysql://root:tomo@discovery-mysql:3306/r2dbc  // System.out.println(@Value("$spring.datasource.url"))
discovery-app_1    | ****************************************************************************************************************
discovery-app_1    | 2021-06-23 16:03:27.354  INFO 1 --- [           main] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 7.10.0 by Redgate
discovery-app_1    | 2021-06-23 16:03:27.469  WARN 1 --- [           main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.spring
framework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfi
guration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1    | Unable to obtain connection from database: Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1    | SQL State  : 08S01
discovery-app_1    | Error Code : 0
discovery-app_1    | Message    : Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    |
discovery-app_1    | 2021-06-23 16:03:27.485  INFO 1 --- [           main] ConditionEvaluationReportLoggingListener :
discovery-app_1    |
discovery-app_1    | Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
discovery-app_1    | 2021-06-23 16:03:27.505 ERROR 1 --- [           main] o.s.boot.SpringApplication               : Application run failed
discovery-app_1    |
discovery-app_1    | org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/Flyw
ayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1    | Unable to obtain connection from database: Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1    | SQL State  : 08S01
discovery-app_1    | Error Code : 0
discovery-app_1    | Message    : Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    |
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:64) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:337) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1336) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1325) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at com.tomoaki3284.HelloWorld.HelloWorldApplication.main(HelloWorldApplication.java:11) ~[classes!/:0.0.1-SNAPSHOT]
discovery-app_1    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
discovery-app_1    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
discovery-app_1    |    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
discovery-app_1    |    at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
discovery-app_1    |    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1    |    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1    | Caused by: org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1    | Unable to obtain connection from database: Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1    | SQL State  : 08S01
discovery-app_1    | Error Code : 0
discovery-app_1    | Message    : Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    |
discovery-app_1    |    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:71) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1    |    at org.flywaydb.core.internal.jdbc.JdbcConnectionFactory.<init>(JdbcConnectionFactory.java:68) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1    |    at org.flywaydb.core.Flyway.execute(Flyway.java:510) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1    |    at org.flywaydb.core.Flyway.migrate(Flyway.java:170) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1    |    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-2.5.0.jar!/:2.5.0]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1    |    ... 24 common frames omitted
discovery-app_1    | Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    |    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:833) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:453) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at org.springframework.jdbc.datasource.SimpleDriverDataSource.getConnectionFromDriver(SimpleDriverDataSource.java:144) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1    |    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:55) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1    |    ... 30 common frames omitted
discovery-app_1    | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
discovery-app_1    |
discovery-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
discovery-app_1    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78) ~[na:na]
discovery-app_1    |    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
discovery-app_1    |    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
discovery-app_1    |    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
discovery-app_1    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.NativeSession.connect(NativeSession.java:144) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:953) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:823) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    ... 37 common frames omitted
discovery-app_1    | Caused by: java.net.ConnectException: Connection refused
discovery-app_1    |    at java.base/sun.nio.ch.Net.connect0(Native Method) ~[na:na]
discovery-app_1    |    at java.base/sun.nio.ch.Net.connect(Net.java:576) ~[na:na]
discovery-app_1    |    at java.base/sun.nio.ch.Net.connect(Net.java:565) ~[na:na]
discovery-app_1    |    at java.base/sun.nio.ch.NiosocketImpl.connect(NioSocketImpl.java:588) ~[na:na]
discovery-app_1    |    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
discovery-app_1    |    at java.base/java.net.Socket.connect(Socket.java:645) ~[na:na]
discovery-app_1    |    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1    |    ... 40 common frames omitted
discovery-app_1    |

// from here, the same log repeatedly because Spring Boot App would restart on failure.

我每次如何推动改变:

mvnw package && java -jar target/spring-boot-0.0.1-SNAPSHOT.jar
docker build -t tomojava3284/helloworldapi .
docker push tomojava3284/helloworldapi:latest
docker-compose pull
docker-compose up

【问题讨论】:

你在应用容器上有重启策略;它最终会出现吗? (可能会在数据库完全初始化之前启动应用程序。) @DavidMaze 我一开始也是这么想的,但是无论我等待 Spring App 重启多少次,它都会产生同样的错误。 我添加了完整的错误以及我如何推动更改(这可能是错误的?)。 【参考方案1】:

我在使用 java 时遇到了同样的问题,我的解决方案是为 docker-compose.yml 中的每个服务设置 IP,如下所示:

version: '3'

services:

  discovery-mysql:
    image: mysql:5.7.34
    container_name: discovery-mysql
    environment:
      - MYSQL_ROOT_PASSWORD=tomo
      - MYSQL_DATABASE=r2dbc
    ports:
      - 3307:3306
    networks:
      common-network:
        ipv4_address: 172.18.0.5

  flyway:
    image: flyway/flyway
    command:
      - url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
    volumes:
      - ./src/main/resources/db/migration:/flyway/sql
      - ./flyway/conf/flyway.config:/flyway.config
    depends_on:
      - discovery-mysql
    networks:
      common-network:
        ipv4_address: 172.18.0.10

  discovery-app:
    image: tomojava3284/helloworldapi:latest
    restart: on-failure
    depends_on:
      - discovery-mysql
    ports:
      - 8001:8080
    environment:
      - spring.datasource.url=r2dbc:mysql://root:tomo@discovery-mysql:3306/r2dbc
    networks:
      common-network:
        ipv4_address: 172.18.0.15

networks:
  common-network:
    ipam:
      config:
        - subnet: 172.18.0.0/16

您的连接网址将是

$ r2dbc:mysql://root:tomo@ 172.18.0.5:3306/r2dbc

注意你使用的IP范围,也许这个不再免费

【讨论】:

不幸的是,它仍然有同样的错误。在 docker-compose 文件上拥有 url-spring.datasource.url=r2dbc:mysql://root:tomo@discovery-mysql:3306/r2dbc 应该保持不变吗?我真的不确定是什么导致了这个错误。

以上是关于Spring Boot,Java,Docker Compose,尝试在两个容器(mysql,my-api)之间建立连接时出现“连接被拒绝”的主要内容,如果未能解决你的问题,请参考以下文章

改进 Docker 中的 Spring-Boot 启动

将命令行参数传递给在 Docker 中运行的 Java 应用程序(Spring Boot)

sh Git + Java + Spring Boot + Kotlin + Python + Node.js + Docker + Docker的安装脚本构建开发环境。

java版spring cloud+spring boot 社交电子商务平台 (二十四)springboot整合docker

PostgreSQL ‘数据库不存在’ - Java Spring Boot、Flyway、Docker/PostgreSQL

Spring Boot MySQL Docker 引起:java.net.ConnectException:连接被拒绝(连接被拒绝)