使用Docker compose连接到另一个容器 [英] Connect to another container using Docker compose

查看:211
本文介绍了使用Docker compose连接到另一个容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一起使用两个容器:一个与Tomcat一起使用,另一个与数据库一起使用。

I need to use two containers together: one with Tomcat and another with a Database.

我创建了以下描述服务的Yaml文件:

I have created the following yaml file which describes the services:

postgredb:
  image: postgres
  expose:
    - 5432
  ports:
    - 5432:5432
  environment:
    - POSTGRES_USER=user
    - POSTGRES_PASSWORD=password
tomcat:
  image:  tomcat
  links:
    - postgredb:db
  ports:
    - 8080:8080

启动docker-compose后,我看到我无法从Tomcat到达数据库,除非我通过docker inspect检索数据库的IP地址,并在将Tomcat连接池配置到数据库时使用它。

After starting docker-compose I can see that I'm not able to reach the Database from Tomcat, unless I retrieve the IP address of the Database (via docker inspect) and use it when configuring Tomcat Connection Pool to the DB.

据我了解,两个容器应该链接在一起并且我希望可以在本地端口5432上找到该数据库,否则在链接容器时看不到什么好处。

From my understanding, the two containers should be linked and I'd expect to find the database on localhost at port 5432, otherwise I see little benefits in linking the containers.

我的理解正确吗?

推荐答案

使用已定义的别名 db在文件中引用数据库主机名。

Use the alias "db" that you have defined in file to refer to the database host name.


链接服务的容器可以通过与别名相同的主机名
访问,如果没有别名则可以访问服务名

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

来源: https://docs.docker.com/compose/compose-file/compose-file-v2/#links

这篇关于使用Docker compose连接到另一个容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆