Docker-撰写MySQL链接失败

时间:2020-01-25 10:36:39

标签: mysql spring-boot docker docker-compose dockerfile

编辑:我设法使其正常运行

我目前正在将docker与Dockerfile和docker-compose.yml结合使用,我正在尝试运行后端,以便可以使用Postman从数据库中获取数据。但是我不断出现通信链接故障 com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

Dockerfile

FROM openjdk:8-jdk-alpine
EXPOSE 8080
ADD /build/libs/assignment_4-0.0.1-SNAPSHOT.jar spring-docker.jar
ENTRYPOINT ["java", "-jar", "spring-docker.jar"] 

docker-compose.yml

version: '3'

services:
  docker-mysql:
    restart: always
    container_name: docker-mysql
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: database
      MYSQL_ROOT_PASSWORD: root
      MYSQL_ROOT_HOST: '%'
    volumes:
      - ./sql:/docker-entrypoint-initdb.d
    ports:
      - "3306:3306"

  app:
    image: springio/docker
    expose:
      - "8080"
    ports:
      - 8080:8080
    environment:
      WAIT_HOSTS: mysql:3306
    depends_on:
      - docker-mysql

application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://docker-mysql:3306/database
spring.datasource.username=root
spring.datasource.password=root

# To keep the database connection alive while idle for a long time 
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

该API是使用Kotlin通过SpringBoot创建的。有人可以帮我弄清楚如何解决此问题吗?

1 个答案:

答案 0 :(得分:0)

要获得正确的服务启动顺序,您需要添加两件事:

  1. 设置容器的名称,以使它们通过这些名称(通过docker bridge)彼此ping通
  2. 强制您的应用在连接之前完全等待数据库。

从这一点来看,您的Dockerfile可能看起来像这样(让我们选择wait-for-it

FROM openjdk:8-jdk-alpine
EXPOSE 8080
RUN apk add --no-cache bash
RUN wget -q https://github.com/vishnubob/wait-for-it/raw/master/wait-for-it.sh -O /usr/bin/wait-for-it && \
    chmod +x /usr/bin/wait-for-it
ADD /build/libs/assignment_4-0.0.1-SNAPSHOT.jar spring-docker.jar
ENTRYPOINT /usr/bin/wait-for-it docker-mysql-container:3306 -t 120 ; java -jar spring-docker.jar

docker-compose.yml应该包括

version: '3'

networks:
  database:

services:
  docker-mysql:
    networks:
      - database
    container_name: docker-mysql-container
    ...

  app:
    networks:
      - database
    container_name: app-container
    ...

然后将application.properties服务的名称docker-mysql替换为容器的名称docker-mysql-container