我使用 docker-compose 運行我的 Golang API 和 PostgreSQL。
我的日志有錯誤connection refused:
db_1 |
db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1 |
api_1 | Unable to connect to database: dial tcp 0.0.0.0:5432: connect: connection refusedartpaper_api_1 exited with code 1
db_1 | 2021-12-26 15:18:35.152 UTC [1] LOG: starting PostgreSQL 14.1 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20211027) 10.3.1 20211027, 64-bit
db_1 | 2021-12-26 15:18:35.152 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
db_1 | 2021-12-26 15:18:35.152 UTC [1] LOG: listening on IPv6 address "::", port 5432
db_1 | 2021-12-26 15:18:35.216 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1 | 2021-12-26 15:18:35.329 UTC [22] LOG: database system was shut down at 2021-12-26 15:05:11 UTC
db_1 | 2021-12-26 15:18:35.515 UTC [1] LOG: database system is ready to accept connections
我的配置:
config := pgx.ConnConfig{
Host: "0.0.0.0",
Port: 5432,
Database: "artpaper",
User: "admin",
Password: "admin1",
}
我認為 docker-compose.yml 或 Dockerfile for API 中的錯誤,因為在正確的埠上docker ps:
0.0.0.0:5432->5432/tcp artpaper_db_1
API 的 Dockerfile:
FROM golang:1.17.5-alpine3.15
WORKDIR /artpaper
COPY ./ ./
RUN go mod download // download dependencies
RUN go build ./cmd/main/main.go // compile code to one binary file
EXPOSE 8080
CMD [ "./main" ] // run binary file
docker-compose.yml:
version: "3.3"
services:
db:
image: postgres:14.1-alpine3.15
volumes:
- ./data/db:/var/lib/postgresql/data
environment:
- POSTGRES_DB=artpaper
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=admin1
ports:
- 5432:5432
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- db
API 配置中的密碼和用戶,如 docker-compose.yml
來自帶有 api 的容器的主機名是 0.0.0.0:5432
uj5u.com熱心網友回復:
在您的 Golang 應用程式中嘗試使用:db:5432,而不是0.0.0.0:5432。
version: '3.8'
services:
db:
image: postgres:14.1-alpine3.15
volumes:
- ./data/db:/var/lib/postgresql/data
environment:
- POSTGRES_DB=artpaper
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=admin1
ports:
- 5432:5432
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- db
debug:
image: postgres:14.1-alpine3.15
command: sleep 1d
嘗試連接到資料庫:
docker-compose up -d
docker-compose exec debug ash -c 'psql -h db -U admin --dbname artpaper'
uj5u.com熱心網友回復:
第一:在配置資料庫主機應該是一個像在 docker-compose.yml 中的資料庫
第二:Postgres 作為程式沒有時間在容器內開啟。我在連接到資料庫之前添加了 api 代碼延遲。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394709.html
標籤:码头工人 docker-compose 文件
上一篇:動態裁剪影像邊框
