在 Docker Compose 中更改 postgres 容器服务器端口

我正在尝试使用 Docker compose 在远程服务器上部署第二个数据库容器。这个 postgreql 服务器运行在端口5433上,而不是第一个 postgreql 容器所使用的端口5432。

当我设置应用程序时,我得到这个错误输出:

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?

我的码头作文档案是:

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

我觉得问题一定是服务器实例上的 postgresql.conf文件,它将端口设置为5432,当我的应用程序试图连接到它时,会导致错误。有没有一种简单的方法可以使用组合文件中的命令来更改端口,而不是使用卷来替换文件?

我正在使用这个工作的正式后容器。

87683 次浏览

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.

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.