前言
同一主机下搭建容器应用栈的环境,只需要完成容器互联来实现容器间的通信即可,这里采用docker run --link
选项建立容器间的互联关系。
docker官方已不推荐使用docker run --link
来链接2个容器互相通信,它最终可能会被移除,但了解其原理,对如何使2个容器之间互相通信还是有帮助的。
1. 跨链接通信
链接允许容器相互发现并将有关一个容器的信息安全地传输到另一个容器。设置链接时,您在源容器和接收容器之间创建了一个管道。然后,接收者可以访问源容器的相关选定数据。要创建链接,请使用--link
标志。
首先,创建一个新容器,一个包含数据库的容器。
docker run -d --name db training/postgres
这将创建一个db从training/postgres
映像调用的新容器,其中包含一个 PostgreSQL 数据库。
现在,创建一个web容器并将其与您的db容器链接。
docker run -d -P --name web --link db:db training/webapp python app.py
这会将web容器与db您之前创建的容器链接起来。该--link
标志采用以下形式:
--link <name or id>:alias
name
是我们source container(源容器 db)的名称,alias
是链接名称,同时把web
称为recipient(接收容器)。
接下来,使用以下命令检查recipient
docker inspect -f "{{ .HostConfig.Links }}" web
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210613195229173.png)
可以看到web容器现在已连接到了db容器,这允许web访问db容器的相关信息。
在我们的案例中,接收容器web可以访问源容器db的相关信息。为此,Docker 在容器之间创建了一个安全隧道,不需要在容器外部公开任何端口。当我们启动 db容器时,我们没有使用-P或-p标志。这是链接的一大好处:我们不需要向网络公开源容器,这里就是 PostgreSQL 数据库不需要暴露到网络。
Docker 通过两种方式向recipient公开source container的连接信息:
- Environment variables,
- Updating the
/etc/hosts
file.
环境变量
翻译后总感觉有些偏差,所以直接引用官方介绍。
Docker creates several environment variables when you link containers. Docker automatically creates environment variables in the target container based on the --link
parameters. It also exposes all environment variables originating from Docker from the source container. These include variables from:
- the
ENV
commands in the source container’s Dockerfile - the
-e
, --env
, and --env-file
options on the docker run command when the source container is started
These environment variables enable programmatic discovery from within the target container of information related to the source container.
Warning
: It is important to understand that all environment variables originating from Docker within a container are made available to any container that links to it. This could have serious security implications if sensitive data is stored in them.
Docker sets an <alias>_NAME
environment variable for each target container listed in the --link
parameter. For example, if a new container called web
is linked to a database container called db
via --link db:webdb
, then Docker creates a WEBDB_NAME=/web/webdb
variable in the web container.
Docker also defines a set of environment variables for each port exposed by the source container. Each variable has a unique prefix in the form:
<name>_PORT_<port>_<protocol>
The components in this prefix are:
- the alias <name> specified in the
--link
parameter (for example, webdb) - the <port> number exposed
- a <protocol> which is either TCP or UDP
Docker 使用这种前缀格式来定义三个不同的环境变量:
- 该
prefix_ADDR
变量包含来自 URL 的 IP 地址,例如WEBDB_PORT_5432_TCP_ADDR=172.17.0.82
。 - 例如,该
prefix_PORT
变量仅包含来自 URL 的端口号WEBDB_PORT_5432_TCP_PORT=5432
。 - 例如,该
prefix_PROTO
变量仅包含来自 URL 的协议WEBDB_PORT_5432_TCP_PROTO=tcp
。
如果容器公开多个端口,则为每个端口定义一个环境变量集。这意味着,例如,如果一个容器公开 4 个端口,Docker 会创建 12 个环境变量,每个端口 3 个。
…
待补充
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)