Docker golang 杜松子酒 postgres

Docker golang gin postgres

我正在尝试使用 Postgres 为 golang 应用设置 docker。 如果我 remove/comment Postgres,go 应用程序在容器中工作正常。同样,我能够启动 Postgres 容器并登录它。我可以 docker- 整理。 但是当我拨打 API 电话时,例如:localhost:3000/api/admin/users。它给出错误:

error: {
        "error": "+dial tcp 127.0.0.1:5432: connect: connection refused"
    }

Postgres 连接字符串是这样的:

connStr := fmt.Sprintf("host=postgres user=anurag password=anu_12345 dbname=bankingapp sslmode=disable")

db, 错误:= sql.Open("postgres", connStr)

Docker 文件

FROM golang:1.13


WORKDIR /go/src/banking-app
COPY . .

RUN go get -d -v ./...
RUN go install -v ./...

CMD ["go" , "run", "main.go"]


docker-compose.yml

version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"
  postgres:
    image: "postgres"
    environment:
      POSTGRES_USER: 'anurag'
      POSTGRES_PASSWORD: 'anu_12345'
      POSTGRES_DB: 'bankingapp'


@Oras ports 提到的,似乎有一些缺失的端口被暴露:5432:5432 只是添加它以从问题中排除端口,也从你的错误中,似乎你的 docker 应用程序容器 依赖于 数据库容器,因此您需要有一种方法来等待数据库容器启动并且您的应用程序容器可以连接它,检查 depends_on docker 撰写:

https://docs.docker.com/compose/compose-file/

version: '3'
services:
web:
  build: .
  ports:
    - "3000:3000"
  depends_on:
    postgres
  restart_policy:
    condition: on-failure
  postgres:
    image: "postgres"
    ports:
      - "3000:3000"
    environment:
      POSTGRES_USER: 'anurag'
      POSTGRES_PASSWORD: 'anu_12345'
      POSTGRES_DB: 'bankingapp'

There are several things to be aware of when using depends_on:

  1. depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

  2. Version 3 no longer supports the condition form of depends_on.

  3. The depends_on option is ignored when deploying a stack in swarm mode with a version 3 Compose file.

根据以上说明,您可能仍然会遇到此问题,但重启策略将重启应用程序容器,您将连接到数据库。

我找到了答案。 只需要重建图像或使用装载加载。 代码未刷新。

抱歉打扰了。