[英]Golang + postgres + docker: Dial tcp 172.18.0.2:5432: connect: connection refused
I'm trying to make a docker-compose from my golang app and postgres database.我正在尝试从我的 golang 应用程序和 postgres 数据库中创建一个 docker-compose。 Here is the code for db initialization:
这是数据库初始化的代码:
db, err := repository.NewPostgresDB(repository.Config{
Host: os.Getenv("DB_HOST"),
Port: viper.GetString("db.port"),
Username: viper.GetString("db.username"),
DBName: viper.GetString("db.dbname"),
SSLMode: viper.GetString("db.sslmode"),
Password: os.Getenv("DB_PASSWORD"),
})
I take host and password from.env:我从 .env 获取主机名和密码:
DB_PASSWORD=qwerty
DB_HOST=db
and from.configs:和来自.configs:
port: "8000"
db:
username: "postgres"
port: "5432"
dbname: "postgres"
sslmode: "disable"
Docker file is not interesting i guess:我猜 Docker 文件不有趣:
FROM golang:1.19-buster
RUN go version
ENV GOPATH=/
COPY ./ ./
# install psql
RUN apt-get update
RUN apt-get -y install postgresql-client
# build go app
RUN go mod download
RUN go build -o balance-app ./cmd/main.go
CMD ["./balance-app"]
Docker-compose has enviromental intructions as well: Docker-compose 也有环保说明:
version: '3.8'
services:
balance-app:
build: ./
command: ./balance-app
ports:
- 8000:8000
depends_on:
- db
environment:
- DB_PASSWORD=qwerty
- DB_HOST=db
db:
restart: always
image: postgres:latest
volumes:
- ./.database/postgres/data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=qwerty
ports:
- 5432
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 3s
I tried to change ports, tried to change host to localhost like it worked on my linux without docker compose(but docker put postgres to 172...), but it always the same error.我尝试更改端口,尝试将主机更改为本地主机,就像它在我的 linux 上工作一样,没有 docker 撰写(但 docker 将 postgres 设置为 172...),但它总是出现相同的错误。 Will be glad if someone could help me, thanks
如果有人能帮助我,我会很高兴,谢谢
The balance-app does not wait the db. balance-app 不等待数据库。 You should probably look at https://docs.docker.com/compose/startup-order/ and use condition: service_healthy in balance-app part.
您可能应该查看https://docs.docker.com/compose/startup-order/并在 balance-app 部分使用 condition: service_healthy。
version: '3.8'
services:
db:
image: postgres:latest
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 3s
balance-app:
...
depends_on:
db:
condition: service_healthy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.