Changing a postgres containers server port in Docker Compose

PostgresqlDockerDocker Compose

Postgresql Problem Overview


I am trying to deploy a second database container on a remote server using Docker compose. This postgresql server runs on port 5433 as opposed to 5432 as used by the first postgresql container.

When I set up the application I get this error output:

web_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  | 	Is the server running on host "db" (172.17.0.2) and accepting
web_1  | 	TCP/IP connections on port 5433?

and my docker compose file is:

db:
  image: postgres:latest
  environment:
    POSTGRES_PASSWORD: route_admin
    POSTGRES_USER: route_admin
  expose:
    - "5433"
  ports:
    - "5433"
  volumes:
    - ./backups:/home/backups
   
web:
  build: .
  command:  bash -c "sleep 5 && python -u application/manage.py runserver 0.0.0.0:8081"
  volumes:
    - .:/code
  ports:
    - "81:8081"
  links:
    - db
  environment:
    - PYTHONUNBUFFERED=0

I feel the issue must be the postgresql.conf file on the server instance having set the port to 5432 causing the error when my app tries to connect to it. Is there a simple way of changing the port using a command in the compose file as opposed to messing around with volumes to replace the file?

I am using the official postgresql container for this job.

Postgresql Solutions


Solution 1 - Postgresql

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.

Solution 2 - Postgresql

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGreenGodotView Question on Stackoverflow
Solution 1 - PostgresqlRobert MoskalView Answer on Stackoverflow
Solution 2 - Postgresqluser3751385View Answer on Stackoverflow