defraggled
defraggled

Reputation: 1218

Why does my docker-compose port config work?

I'm in the process of creating a docker-compose config which maintains:

  1. a node.js server, and
  2. a separate postgres server.

Tutorials emphasise that postgres port 5432 must be exposed or forwarded so that the node container can access it: facilitated in the below docker-compose.yml.

version: "3.7"

services:
    db:
        container_name: db
        image: postgres:alpine
        ports:
            - "5010:5432"
        environment:
            POSTGRES_USER: postgres
            POSTGRES_PASSWORD: verysecretpass
            POSTGRES_DB: pg-dev

    server:
        container_name: dashboard-api
        build: .
        volumes:
            - .:/server
        ports:
            - "5000:5000"

This produces the below docker ps output:

CONTAINER ID   IMAGE             COMMAND                  CREATED         STATUS         PORTS                    NAMES
0d790cd4929e   server_server     "docker-entrypoint.s…"   4 minutes ago   Up 4 minutes   0.0.0.0:5000->5000/tcp   dashboard-api
818296c1fc02   postgres:alpine   "docker-entrypoint.s…"   7 minutes ago   Up 4 minutes   0.0.0.0:5010->5432/tcp   pg

In the above state, node gets ECONN REFUSED when attempting to connect with this url: postgres://postgres:verysecretpass@db:5010/pg-dev

Yet, the same connection string can connect when using 5432 instead of 5010.

In fact, using 5432, connection succeeds even when pg container has no port configuration whatsoever. The below docker ps output reflects no-port-config state in which node container can happily connect:

CONTAINER ID   IMAGE             COMMAND                  CREATED         STATUS         PORTS                    NAMES
76da96c15c05   server_server     "docker-entrypoint.s…"   7 seconds ago   Up 7 seconds   0.0.0.0:5000->5000/tcp   dashboard-api
51c221ac2c54   postgres:alpine   "docker-entrypoint.s…"   8 seconds ago   Up 7 seconds   5432/tcp                 db

Why does this work? What am I missing here?

Using:

Upvotes: 0

Views: 75

Answers (1)

timsmelik
timsmelik

Reputation: 742

Unless otherwise configured, the services in a docker-compose document are automatically added to a network. There's no need to expose ports in this network.

If you want to expose ports on a container to the outside world, you will need to explicitly map these as you did. This however does not change anything for communication between services in the same network. If you have no reason to access the database from outside the network (e.g. inspect data using a DB tool on your own machine), you don't have to map / expose any ports of the db container.

Upvotes: 1

Related Questions