How to connect to postgresql in docker

1.8k Views Asked by At

I have a postgresql db running in a docker container on my machine. I started it with this run command.

docker run -p 5432:5432 -d \
-e POSTGRES_PASSWORD=$PG_PASS \
-e POSTGRES_USER=$PG_USER \
-e POSTGRES_DB=$PG_NAME \
-v pgdata:/var/lib/postgresql/data \
--name $PG_CONTAINER_NAME \
postgres:alpine

I have confirmed that this created the db using the environment variables by also running a pgadmin4 container and connecting to this container using its container name.

Now I am trying to connect my express app to the db. I am using a orm called mikroorm. The ts code is

const orm = await MikroORM.init({
    dbName: 'ketopal',
    user: 'ketopaladmin',
    password: 'ketopaladmin',
    type: 'postgresql',
    debug: !__prod__,
    entities: [Post],
    host: '172.17.0.2',
    port: 5432
})

This produces a one line error,

MikroORM failed to connect to database ketopal on postgresql://ketopaladmin:*****@172.17.0.2:5432

But I don't know why or how to fix it. 172.17.0.2 is the IP docker gave to the container.

In my perfect world, you all could tell me how to get docker to make localhost:5432 point to the docker container, but any help would be appreciated.

1

There are 1 best solutions below

0
On

Thought I'd document here incase someone also runs into this. I had a local postgres process running on port 5432, so when I attempted to "publish" the container to that same port, it failed to do so, even though it created the container and was otherwise working. I adjusted the run command to map port 54321 to 5432.

docker run -p 54321:5432 -d \
-e POSTGRES_PASSWORD=$PG_PASS \
-e POSTGRES_USER=$PG_USER \
-e POSTGRES_DB=$PG_NAME \
-v pgdata:/var/lib/postgresql/data \
--name $PG_CONTAINER_NAME \
postgres:alpine

TLDR; If you have something running that already claimed a port, running a container on that port won't work.