11.7. 使用端口映射在容器间通信
在两个容器之间进行通信的最方便方法是使用公布的端口。可使用两种方式发布端口:自动或手动发布。
先决条件
-
container-tools
元数据包已安装。
流程
运行未发布的容器:
# podman run -dt --name=web1 ubi9/httpd-24
运行自动发布的容器:
# podman run -dt --name=web2 -P ubi9/httpd-24
运行手动发布的容器并发布容器端口 80:
# podman run -dt --name=web3 -p 9090:80 ubi9/httpd-24
列出所有容器:
# podman ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f12fa79b8b39 registry.access.redhat.com/ubi9/httpd-24:latest /usr/bin/run-http... 23 seconds ago Up 24 seconds ago web1 9024d9e815e2 registry.access.redhat.com/ubi9/httpd-24:latest /usr/bin/run-http... 13 seconds ago Up 13 seconds ago 0.0.0.0:43595->8080/tcp, 0.0.0.0:42423->8443/tcp web2 03bc2a019f1b registry.access.redhat.com/ubi9/httpd-24:latest /usr/bin/run-http... 2 seconds ago Up 2 seconds ago 0.0.0.0:9090->80/tcp web3
您可以看到:
-
容器
web1
没有公布的端口,只能通过容器网络或网桥访问。 容器
web2
已自动映射端口 43595 和 42423,以分别发布应用端口 8080 和 8443。注意可能会出现自动端口映射,因为
registry.access.redhat.com/9/httpd-24
镜像在 Containerfile 中具有EXPOSE 8080
和EXPOSE 8443
命令。-
容器
web3
有一个手动发布的端口。主机端口 9090 映射到容器端口 80。
-
容器
显示
web1
和web3
容器的 IP 地址:# podman inspect --format='{{.NetworkSettings.IPAddress}}' web1 # podman inspect --format='{{.NetworkSettings.IPAddress}}' web3
使用 <IP>:<port> 表示法访问
web1
容器:# curl 10.88.0.14:8080 ... <title>Test Page for the HTTP Server on Red Hat Enterprise Linux</title> ...
使用 localhost:<port> 表示法访问
web2
容器:# curl localhost:43595 ... <title>Test Page for the HTTP Server on Red Hat Enterprise Linux</title> ...
使用 <IP>:<port> 表示法访问
web3
容器:# curl 10.88.0.14:9090 ... <title>Test Page for the HTTP Server on Red Hat Enterprise Linux</title> ...