[英]Not able to connect to Postgres container from another container
這個問題已經在這里、 這里和這里被問過很多次了,但是這些解決方案對我不起作用。
我用這個docker-compose.yml
文件創建了一個 Postgres 和一個 AppServer 容器
version: "3.7"
services:
db:
image: postgres:alpine
container_name: db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydb
POSTGRES_INITDB_ARGS: '-A md5'
volumes:
- ./pgdata:/var/lib/postgressql/data
ports:
- "5432:5432"
api:
build: api
container_name: api
volumes:
- ./database/migrations:/migrations
ports:
- "8080:8080"
links:
- db
depends_on:
- db
運行此之后,我可以成功
docker exec -it db psql -U user mydb
我成功連接到 Postgres。 我也可以成功登錄到兩個容器的終端
docker exec -it api bash
docker exec -it db bash
從 api 的 bash 內部我可以毫無問題地 ping db
但是,從我的 api 容器中,我無法建立到 Postgres 數據庫的 JDBC 連接。
api | Flyway Community Edition 7.3.2 by Redgate
api | ERROR:
api | Unable to obtain connection from database (jdbc:postgresql://db:5432/mydb) for user 'user': Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
api | SQL State : 08001
api | Error Code : 0
api | Message : Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api |
api | Caused by: org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | Caused by: java.net.ConnectException: Connection refused (Connection refused)
當我可以通過 psql 連接時,為什么連接被拒絕? 這是我的飛行路線
flyway.url=jdbc:postgresql://db:5432/mydb
flyway.user=user
flyway.password=password
flyway.locations=filesystem:/migrations
編輯:: 所以如果我等待一段時間后從docker exec -it api bash
flyway migrate
一切正常。 我認為上面發生的事情是我的flyway migrate
命令甚至在數據庫准備好之前就正在運行。
為什么會這樣? 因為我已經指定了依賴項,所以我的 API 容器應該僅在數據庫完全啟動時啟動。 但似乎並非如此。
將數據庫容器指定為依賴項並不能保證它會在您的其他服務/容器之前准備好。 它只保證它將在您的其他服務之前啟動。
解決此問題的一種方法是在啟動期間無法連接到數據庫時在 API 應用程序中實施重試嘗試。
這是一篇文章的鏈接,該文章使用 shell 腳本等待服務就緒。
IMO 您的應用程序應該足夠聰明,可以在無法建立數據庫連接時重試幾次。 無論如何,它將使它更加健壯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.