连接两个容器失败

Connect two containers between them failed

我在尝试同时管理 docker-compose 和 dockerfile 时遇到了一些问题。 我研究过,我知道可以在没有 docker 文件的情况下使用 docker-compose,但我认为对我来说最好也使用 Dockerfile,因为我希望环境易于修改。 问题是我想要一个带有 postgres 的容器,它是另一个容器的依赖组件,名为 api 的容器用于 运行 应用程序。 此容器包含 Java 17 和 Maven 3,并使用 docker-compose 从 Dockerfile 获取图像。问题是:当我使用 Dockerfile 时,一切都很好,但实际上当我使用 docker-compose 时,我得到了这个错误: 2021-12-08T08:36:37.221247254Z /usr/local/bin/mvn-entrypoint.sh: line 50: exec: mvn test: not found

配置文件是:

FROM openjdk:17-jdk-slim

ARG MAVEN_VERSION=3.8.4
ARG USER_HOME_DIR="/root"
ARG SHA=a9b2d825eacf2e771ed5d6b0e01398589ac1bfa4171f36154d1b5787879605507802f699da6f7cfc80732a5282fd31b28e4cd6052338cbef0fa1358b48a5e3c8
ARG BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries

RUN apt-get update && \
    apt-get install -y \
      curl procps \
  && rm -rf /var/lib/apt/lists/*

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && curl -fsSL -o /tmp/apache-maven.tar.gz ${BASE_URL}/apache-maven-${MAVEN_VERSION}-bin.tar.gz \
  && echo "${SHA}  /tmp/apache-maven.tar.gz" | sha512sum -c - \
  && tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \
  && rm -f /tmp/apache-maven.tar.gz \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

COPY mvn-entrypoint.sh /usr/local/bin/mvn-entrypoint.sh
COPY settings-docker.xml /usr/share/maven/ref/

COPY . .

RUN ["chmod", "+x", "/usr/local/bin/mvn-entrypoint.sh"]

ENTRYPOINT ["/usr/local/bin/mvn-entrypoint.sh"]

CMD ["mvn", "test"]

和docker-编写文件:


services:
  api_service:
    build:
      context: .
      dockerfile: Dockerfile
    restart: always
    container_name: api_core_backend
    ports:
      - 8080:8080
    depends_on:
      - postgres_db

  postgres_db:
    image: "postgres:latest"
    container_name: postgres_core_backend
    restart: always
    ports:
      - 5432:5432
    environment:
      POSTGRES_DB: postgres
      POSTGRES_PASSWORD: root

谁能解释一下为什么我在使用 docker-compose 执行时出现错误,但如果我改用 dockerfile 则一切正常? 谢谢。

更新:Link 尝试连接到另一个容器时出错:

Caused by: org.flywaydb.core.internal.exception.FlywaySqlException: 
Unable to obtain connection from database: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SQL State  : 08001
Error Code : 0
Message    : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

问题

根据 the logs,问题似乎是您在连接时使用 localhost 作为主机名。

Docker compose 创建一个内部网络,其中主机名映射到服务名称。所以在你的例子中,主机名是 postgres_db.

请参阅 docker compose docs 了解更多信息。

解决方案

尝试指定 postgres_db 作为主机名:)