我用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中的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
3条答案
按热度按时间ehxuflar1#
在你的Golang应用程序中尝试使用:db:5432,not0.0.0.0:5432.
尝试连接到以下数据库:
docker-compose up -d
docker-compose exec debug ash -c 'psql -h db -U admin --dbname artpaper'
des4xlb02#
第一:在配置数据库主机应该是一个数据库一样,在docker-compose.yml
第二:Postgres作为一个程序没有时间在容器内打开。我在API代码中添加了连接数据库之前的延迟。
wswtfjt73#
我也有类似的问题,并找到了原因,并希望分享给未来的读者。
容器之间的内部通信发生在Docker网络中,而不是通过主机的端口。当内容服务尝试连接到content-db容器时,它是通过Docker网络连接的,其中数据库仍然在其默认端口5432上侦听。