docker compose:spring boot 连接到 mysql 数据库被拒绝

2021-12-26 00:00:00 docker docker-compose mysql spring-boot

我对 Docker 还很陌生,我需要在 docker 工具箱上使用 docker-compose 启动我的 Angular/SpringBoot/MySQL 项目.我将一个 docker yml 文件复制到我的项目中,该文件使用相同的技术并更改了其中的路径以匹配我的项目.但是,当我尝试 docker-compose 时,它​​会引发以下错误:

I'm pretty new to Docker and I need to startup my Angular/SpringBoot/MySQL project with docker-compose on the docker toolbox. I copied a docker yml file into my project which used the same technologies and changed the paths inside of it to match my project. However when I try docker-compose, it throws the following error:

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
[...] 84 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)

docker-compose.yml 看起来像:

the docker-compose.yml looks like:

version: '3'

services:
  database:
    image: mysql
    container_name: database
    environment:
      MYSQL_ROOT_PASSWORD: ****
      MYSQL_DATABASE: db_example
      MYSQL_USER: springuser
      MYSQL_PASSWORD: ****
    ports:
      - 3306:3306
    volumes:
      - db_exampleData:/var/lib/mysql

  springapi:
    image: openjdk:10-jre-slim
    container_name: springapi
    ports:
      - 8443:8443
    depends_on:
      - database
    volumes:
      - ./backend/target/backend-0.1.0.jar:/application.jar
    command: ["java", "-jar", "application.jar"]

  angular:
    image: nginx:alpine
    container_name: angular
    ports:
      - 4200:80
    depends_on:
      - springapi
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./frontend/my-app/dist/my-app:/usr/share/nginx/html

volumes:
  db_exampleData:

application.properties:

the application.properties:

spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=****

server.port=8443

任何建议都会有所帮助!

any suggestion would be helpful!

推荐答案

你需要像这样改变你的连接:

you need to change your connecion like this:

jdbc:mysql://database:3306/db_example

并将其添加到 springapi 服务下的 docker-compose 中:

and add this to your docker-compose under springapi service:

links:
   - database

另一方面,您可以使用 wait-for-it.sh 通过在 springapi 服务下添加命令部分来检查数据库是否已启动:

on the other hand you may use wait-for-it.sh to check if DB is up by add a command section under springapi service:

command: ["path/to/wait-for-it.sh", "database:3306", "-t", "6000", "--", "YOUR ACTUAL COMMAND"]

相关文章