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

Docker中Liquibase连接PostgreSQL报错:连接无法创建

Docker环境下Liquibase连接PostgreSQL被拒绝问题解决

问题场景

在Docker环境中通过Liquibase执行PostgreSQL数据库迁移操作时,出现连接拒绝错误,但使用相同凭证可通过pgAdmin连接该Docker容器中的PostgreSQL数据库,查阅相关资料后仍未解决。

错误日志

app-liquibase  | Liquibase Version: 4.30.0
app-liquibase  | Liquibase Open Source 4.30.0 by Liquibase
app-liquibase  | ERROR: Exception Details
app-liquibase  | ERROR: Exception Primary Class:  ConnectException
app-liquibase  | ERROR: Exception Primary Reason:  Connection refused
app-liquibase  | ERROR: Exception Primary Source:  4.30.0
app-liquibase  | 
app-liquibase  | Unexpected error running Liquibase: Connection could not be created to jdbc:postgresql://localhost:5432/shopping with driver org.postgresql.Driver.  Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
app-liquibase  |   - Caused by: Connection refused
app-liquibase  | 
app-liquibase  | For more information, please use the --log-level flag
app-liquibase exited with code 1
Aborting on container exit...

现有docker-compose配置

services:
  app:
    build: ./
    container_name: app-server
    volumes:
      - ./:/app-server
    ports:
      - 8080:8080
    expose:
      - 8080
    networks:
      - ktor-network
    depends_on:
      - database
  database:
    image: postgres:latest
    container_name: app-db
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: mydb
    ports:
      - 5432:5432
    expose:
      - 5432
    networks:
      - ktor-network
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U postgres" ]
      interval: 5s
      timeout: 5s
      retries: 5
  database-migration:
    image: liquibase/liquibase:latest
    container_name: app-liquibase
    volumes:
      - ./app/src/main/resources/liquibase/:/liquibase/changelog
    command: ["--url=jdbc:postgresql://localhost:5432/mydb", "--username=postgres", "--password=postgres", "--changelog-file=liquibase/changelog/changelog.xml", "update"]
    depends_on:
      database:
        condition: service_healthy
    networks:
      - ktor-network
networks:
  ktor-network:
    driver: bridge

解决方案

核心问题

容器内的localhost指向容器自身,而非宿主机或其他容器。在Docker Compose的同一自定义网络中,容器之间需要通过服务名称互相访问,而非localhost。

具体修改

将database-migration服务的JDBC URL中的localhost替换为PostgreSQL服务的名称database(对应docker-compose配置中services下的服务名):

修改后的database-migration服务command配置:

command: ["--url=jdbc:postgresql://database:5432/mydb", "--username=postgres", "--password=postgres", "--changelog-file=liquibase/changelog/changelog.xml", "update"]

额外注意

错误日志中显示Liquibase尝试连接的数据库是shopping,但docker-compose中PostgreSQL初始化的数据库是mydb,需确保两者名称一致,避免后续出现数据库不存在的错误。

内容的提问来源于stack exchange,提问作者User2403

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:40:12