我有一个 Spring - Postgres 项目,我用 Docker Compose 对其进行了容器化。
这是我的撰写文件:
services:
db:
container_name: astro_db
image: postgres:latest
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=astro
user: postgres
ports:
- "5432:5432"
volumes:
- ./postgres/init/:/docker-entrypoint-initdb.d/
- ./postgres/data/:/var/lib/postgresql/data/
networks:
- mynet
healthcheck:
test: [ "CMD-SHELL", "pg_isready -d astro -U postgres"]
interval: 10s
timeout: 5s
retries: 5
astro:
container_name: astro_app
build:
context: .
dockerfile: Dockerfile
ports:
- '8081:8080'
depends_on:
db:
condition: service_healthy
env_file: .env
networks:
- mynet
networks:
mynet:
driver: bridge
name: astro_net
此外,这是我的 Spring
application.yml
文件:
server:
port: 8080
spring:
application:
name: Astro
datasource:
url: jdbc:postgresql://db:5432/astro
username: postgres
password: postgres
jpa:
hibernate:
ddl-auto: update
show-sql: true
open-in-view: false
sql:
init:
platform: postgresql
schema-locations: classpath:/db_init/schema.sql
session:
jdbc:
initialize-schema: always
logging:
level:
root: warn
web: debug
hibernate: error
当我使用
docker-compose up
启动项目时,即使我在 Docker-Compose 上获得了 Connection refused
标签,甚至将服务名称作为主机(正如在许多类似情况下所建议的那样),我也会遇到 depends_on
错误).
当我仅为 Postgres 启动一个容器并通过 IntelliJ Spring 运行按钮启动我的应用程序时,当主机为 localhost 时,它可以完美运行。但是当我开始使用docker组合,将主机更改为服务名称时,出现了问题......
我的 Postgres 已成功启动,因为:database system is ready to accept connections
(它说在 5432 端口)。我已经做了很多很多网站,但没有找到适合我的情况的可行解决方案。
提前致谢!
PS:很少的信息:
init.sql
,确保我的数据库和用户存在
Dockerfile
,但没有 Postgres,似乎没有帮助
我刚刚修好了。我不知道这是否是完美的方法,但它确实有效(笑)。
我“只是”必须在我的
FROM ubuntu:20.04
的开头添加
Dockerfile
(对于 Spring)。我想通了,因为@Zapl评论尝试ping:在shell中没有
ping
,
apt
,...所以我安装了Ubuntu并且它被修复了(我猜我复制了错误的Dockerfile模板互联网)。
FROM ubuntu:20.04 # Forgotten line (lol)
FROM eclipse-temurin:17-jdk-focal
# Install Maven
FROM openjdk:22-ea-28-jdk
WORKDIR /app
EXPOSE 8080
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY src ./src
CMD ["./mvnw", "spring-boot:run"]
谢谢!