在docker-compose中,如何将一个容器中的应用程序连接到另一个容器中的postgres数据库

我是docker工的初学者,是docker工作者的新手。 我正在尝试运行docker撰写的项目。 当我的后端应用程序试图连接到数据库,我得到这个错误:

org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. 

你能看到我的撰写文件有可能导致它不能连接的任何错误吗?

 version: "3" services: db: image: postgres volumes: - data-volume:/var/lib/db ports: - "5432" backup: image: ubuntu volumes: - data-volume:/var/lib/backup/data backend: image: java restart: always volumes: - data-volume:/var/lib/backup/data - ~/code/myCode:/usr/src/app/ command: sh /usr/src/app/Docker/docker-setup.sh expose: - "8000" volumes: data-volume: 

您的数据库不在您的Java容器的localhost中。 您可以将Javaconfiguration指向Postgres,如下所示: db:5432您也可以从Java容器到db的链接按顺序启动:

 backend: image: java links: - db (...the rest...) 

也许你需要等到Postgres Java开始之前打开它的端口5432(我不知道它是否是强制的)。 如果你需要的话,常用的方法是添加一个wait-for-it.sh脚本(在GitHub上可用),修改命令:

command: /wait-for-it.sh db:5432 -- sh /usr/src/app/Docker/docker........