我应该在 docker-compose.yml 中提供什么配置以允许 spring boot docker 容器连接到远程数据库?

问题描述

我尝试使用以下 docker compose 文件启动 2 个容器:

version: '2'

services:
  client-app:
    image: client-app:latest
    build: ./client-app/Dockerfile
    volumes:
      - ./client-app:/usr/src/app
    ports:
      - 3000:8000

  spring-boot-server:
    build: ./spring-boot-server/Dockerfile
    volumes:
      - ./spring-boot-server:/usr/src/app
    ports:
      - 7000:7000

spring boot 服务器尝试连接到另一个主机和网络上的远程数据库服务器。 Docker 成功启动 client-app 容器,但未能启动 spring-boot-server。此日志显示服务器因无法连接到远程数据库而崩溃:

2021-01-25 21:02:28.393  INFO 1 --- [main] com.zaxxer.hikari.HikariDataSource: HikariPool-1 - Starting...
2021-01-25 21:02:29.553 ERROR 1 --- [main] com.zaxxer.hikari.pool.HikariPool: HikariPool-1 - Exception during pool initialization.

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.

两个容器的 Dockerfile 都创建了有效的镜像,我可以通过这些镜像手动运行容器。看起来对由组合文件启动的容器有一些认的网络限制。

在 Ubuntu 上运行的 Docker 组合版本:

docker-compose version 1.8.0,build unkNown

==============================================>

进一步调查:

我创建了一个 Dockerfile

FROM ubuntu
RUN apt-get update
RUN apt-get install -y MysqL-client
CMD MysqL -A -P 3306 -h 8.8.8.8 --user=root --password=mypassword -e "SELECT VERSION()" mydatabase

连同 docker-compose.yml

version: '2'
services:
  test-remote-db-compose:
    build: .
    ports:
      - 8000:8000

单独测试与远程数据库的连接。测试成功通过。

解决方法

问题已经解决了,执行 this 后,主机重新启动并docker-compose up --build