I am having this weird error using Postgres with Docker. So, I have two services in my docker-compose file:
version: '3'
services:
db:
image: postgres
restart: always
ports:
- '5432:5432'
environment:
POSTGRES_PASSWORD: pass123
test-db:
image: postgres
restart: always
ports:
- '5433:5433'
environment:
POSTGRES_PASSWORD: pass123
So, when I run "docker-compose up -d", both containers get mounted. The command "docker ps" gives me:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a76fcc56f928 postgres "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp nodejs-nest_iluvcoffe_db_1
9ab54557063f postgres "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 5432/tcp, 0.0.0.0:5433->5433/tcp, :::5433->5433/tcp nodejs-nest_iluvcoffe_test-db_1
When i try to connect to the container mapping the port 5432->5432, is all good. But when i try to connect to the container mapping the port 5433->5433 I get the error:
server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.
But, if I map the ports like:
version: '3'
services:
db:
image: postgres
restart: always
ports:
- '5432:5432'
environment:
POSTGRES_PASSWORD: pass123
test-db:
image: postgres
restart: always
ports:
- '5433:5432'
environment:
POSTGRES_PASSWORD: pass123
Then, I will have in my "docker ps":
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5228461a2cff postgres "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp nodejs-nest_iluvcoffe_db_1
39353d05004c postgres "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:5433->5432/tcp, :::5433->5432/tcp nodejs-nest_iluvcoffe_test-db_1
And I can connect to both containers/postgres-servers. Someone know why that? why I cant use the 5433->5433 ports mapping?
CodePudding user response:
Postgresql
service listens on port5432
within your container.ports
section with5433->5432
meansmap host port 5433 to listening container port 5432
As a result, mapping 5433 on 5433 is not possible without changing port listening inside postgresql container.
- Each container is like a single host, modifying listening port within
posgresql container
should not be necessary.
Please check this documentation for more information on postgresql default settings : https://www.postgresql.org/docs/current/runtime-config-connection.html
CodePudding user response:
I believe i understood what is happening. Inside the container, by default, postgres will run on port 5432, even if i map on the ports directive:
ports:
- '5433:5433'
To tell postgres which port to run inside the container, i used the setup below:
version: '3'
services:
db:
image: postgres
restart: always
ports:
- '5432:5432'
environment:
POSTGRES_PASSWORD: pass123
test-db:
image: postgres
restart: always
ports:
- '5433:5433'
environment:
POSTGRES_PASSWORD: pass123
command: -p 5433
And everything is working now