Changing a postgres containers server port in Docker Compose Changing a postgres containers server port in Docker Compose docker docker

Changing a postgres containers server port in Docker Compose


I'm assuming postgres is running on port 5432 in the container and you want to expose it on the host on 5433.

This ports strophe:

ports:    - "5433:5432"

will expose the server on port 5433 on the host. You can get rid of your existing expose strophe in this scenario.

If you only want to expose the service to other services declared in the compose file (and NOT localhost), just use the expose strophe and point it to the already internally exposed port 5432.

Bear in mind, the EXPOSE directive doesn't actually do anything (it's more of a hint for you). Port 5432 will be exposed to the other services declared in the compose file with or without the directive.


Some people may wish to actually change the port Postgres is running on, rather than remapping the exposed port to the host using the port directive. To do so, use command: -p 5433

In the example used for the question:

db:  image: postgres:latest  environment:    POSTGRES_PASSWORD: route_admin    POSTGRES_USER: route_admin  expose:    - "5433" # Publishes 5433 to other containers but NOT to host machine  ports:    - "5433:5433"  volumes:    - ./backups:/home/backups  command: -p 5433

Note that only the host will respect the port directive. Other containers will not.