Search code examples
databasepostgresqlgoconnection

postgres doesn't work inside docker container


I've been developing a webpage with golang using Postgres. I could run the app without a docker container and I could connect to the database, no problem occurred. However, when I dockerized my app and run it, Postgres showed an error: dial tcp 127.0.0.1:5432: connect: connection refused.

Connecting to postgres:

db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")

I searched for the internet and found that inside the container localhost will direct to the container. I tried to connect specifying the IP of my server:

db, err := sql.Open("postgres", "host=XXX.XXX.XX.XXX port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")

it also showed the same error: dial tcp XXX.XXX.XX.XXX:5432: connect: connection refused

when I run it without dockerizing it works fine. What to do?

Here is my dockerfile. I was just trying to upload the simplest app to the dedicated server. I logged in using ssh root@IP and installed go and postgres. I pulled my app to the server and then started it with just go build and ./app. Everything worked fine. Now I wanna run it using the dockerfile below.

FROM golang:alpine RUN mkdir /app ADD . /app WORKDIR /app COPY go.mod . RUN go mod download COPY . . RUN go build -o main . CMD ["/app/main"]


Solution

  • After thoroughly checking the comments by @colm.anseo, I figured out how to access the host machine in the docker container. I used the flag --network="host" to run my docker container. So I used: docker run -it --network="host" myapp to run the container. As I understood, this will bind the IP of the docker container and host machine

    you can read more about it in: From inside of a Docker container, how do I connect to the localhost of the machine?