Home > Net >  unable to properly expose Postgres with Docker Compose
unable to properly expose Postgres with Docker Compose

Time:11-28

I'm trying to connect to Postgres running on a remote server via PGAdmin. I am using Wireguard to VPN into the network.

I can connect over 5432, but I'm not sure how as I don't expose this port.

version: '3.8'
services:
  db_staging:
    image: postgres:14.1-alpine
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    expose:
      - 8100
    ports:
      - 8100:5432
    volumes: 
      - db_staging:/var/lib/postgresql/data
    networks:
      containernet:
        ipv4_address: 192.168.160.10
volumes:
  db_staging:
    driver: local

networks:
  containernet:
    external:
      name: vpn_containernet

On the subnet containernet, I pick a static IP and use this as the host IP to connect to. I use 8100 and get connection refused. When I use 5432 the in PGAdmin and PSQL is established without error, but why?

CodePudding user response:

On containernet you use the unmapped ports and there's no need to map the ports to be able to access the containers.

The mapping maps the port to a port on the host machine. You only need to map the port if you need the container to be available using the host machine's IP address. And then you'd use port 8100.

You can use this to only expose ports that are 'user facing'. For instance you might have a database container, a backend and a frontend container. Since you only need to interact with the frontend container, you only need to map a port on the frontend container to the host machine.

On the docker network, the containers can still talk to each other using their unmapped ports.

  • Related