You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker启动Spring Boot+Postgres项目时用户与数据库未自动创建问题咨询

问题根因
  • 你提供的配置文件存在多处YAML缩进错误,配置没有被正确加载:
    • docker-compose.yml中postgres服务的层级、环境变量配置缩进错误,POSTGRES_*初始化参数没有生效
    • application.yml中JPA、数据源、Liquibase配置错误缩进至config.activate层级下,Spring Boot无法读取到正确的数据库连接参数
  • 本地残留之前运行postgres容器生成的Docker卷,postgres仅在首次初始化时会读取POSTGRES_*环境变量创建库和用户,旧卷存在时会直接加载历史数据跳过初始化
  • 原生depends_on仅保证容器启动顺序,无法保证postgres初始化完成后再启动Spring Boot服务,容易出现服务提前发起连接的报错
解决方案

1. 修正配置文件缩进

修正后的docker-compose.yml

新增postgres健康检查,保证postgres完全初始化完成后再启动微服务:

version: '3'
services:
  microservice:
    build: ./
    image: someimage
    ports:
      - "8080:8080"
    environment:
      MEMORY_OPTS: "-Xmx512M"
      PG_DB_HOST: postgres
      PG_DB_PORT: 5432
      PG_DB_PASSWORD: postgres
    depends_on:
      postgres:
        condition: service_healthy
  postgres:
    image: postgres:10.4-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: db
    ports:
      - "5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

修正后的application.yml

调整配置层级到spring根节点下:

spring:
  config:
    activate:
      on-profile: local
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: update
    show-sql: true
  datasource:
    url: jdbc:postgresql://postgres:5432/db
    username: postgres
    password: postgres
  liquibase:
    change-log: classpath:/db/changelog/db.changelog-master.yaml

2. 清理历史残留数据

执行以下命令停止现有容器并删除关联的历史卷:

docker compose down -v

3. 重新启动服务

执行以下命令重新构建并启动所有服务:

docker compose up --build

内容的提问来源于stack exchange,提问作者Дмитрий Фактов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:54:03