简体   繁体   中英

Docker golang gin postgres

I am trying to set up a docker for golang app with Postgres. The go app works fine in a container if I remove/comment Postgres. And similarly, I am able to spin up Postgres container and log into it. I am able do docker-compose up. But when I make a API call, like for eg: localhost:3000/api/admin/users . It gives and error:

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

The Postgres connection string is like this:

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

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

Dockerfile

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'


Seems to be some missing ports to be exposed as mentioned by @Oras ports: 5432:5432 just add it to exclude ports from the issue, also from the error you have, it seems that your docker app container depends on the database container so you need to have a way to wait until your database container is up and your app container can connect it, check depends_on for docker compose:

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.

and based on the the above note you may still face the issue for but the restart policy will restart the app container and you will connect to the database.

I found the answer. Just need to rebuild image or load using mount. The code was not refreshed.

Sorry to bother.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM