当尝试使用 2 个容器运行 docker-compose 时,java 容器由于某种原因会敲击 localhost:5432,尽管我指定了不同的环境变量:
Dockerfile:
FROM openjdk:22
ARG APP_JAR=target/*.jar
ADD ${APP_JAR} course.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "course.jar"]
docker-compose.yml:
version: "3.9"
services:
course_pg_17:
image: postgres
restart: always
container_name: course_pg_17
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB:
app:
build:
dockerfile: Dockerfile
container_name: app
expose:
- "8080"
ports:
- "8081:8080"
environment:
DB_USER: postgres
DB_PASSWORD: postgres
DB_URL: jdbc:postgresql://course_pg_17:5432/postgres
depends_on:
- course_pg_17
应用程序属性:
spring.application.name=course
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.datasource.url=${DB_URL}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
server.port=8080
当我尝试使用 postgresql 启动容器时,它会上升,但 spring 会因错误而崩溃
2024-10-22T18:47:25.453265300Z 2024-10-22T18:47:25.453Z ERROR 1 --- [course] [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
按照评论中的建议,我通过这种方式向 Dockerfile 添加了变量,但没有解决问题:
ENV DB_USER=postgres
ENV DB_PASSWORD=postgres
ENV DB_URL=jdbc:postgresql://course_pg_17:5432/postgres