首页 > 解决方案 > 将容器端口暴露给特定主机 IP

问题描述

我可以在运行时将容器端口转发到全局主机 IP:

docker run -p IP:5000:5000 container_name

或在 docker-compose 中:

ports:
- "5000:5000"`

但是,以下将主机的端口打开到所有外部 IP 地址。如何使 IP 地址为 X 且没有其他 IP 地址的主机 A 可以访问该端口?

标签: dockerdocker-composedockerfile

解决方案


查看文档:在指定格式时,您还可以提及要绑定到哪个 IP 地址。(默认是绑定所有 IP-Address-0.0.0.0)

EXPOSE (incoming ports)
The following run command options work with container networking:

--expose=[]: Expose a port or a range of ports inside the container.
             These are additional to those exposed by the `EXPOSE` instruction
-P         : Publish all exposed ports to the host interfaces
-p=[]      : Publish a container᾿s port or a range of ports to the host
               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
               Both hostPort and containerPort can be specified as a
               range of ports. When specifying ranges for both, the
               number of container ports in the range must match the
               number of host ports in the range, for example:
                   -p 1234-1236:1234-1236/tcp

               When specifying a range for hostPort only, the
               containerPort must not be a range.  In this case the
               container port is published somewhere within the
               specified hostPort range. (e.g., `-p 1234-1236:1234/tcp`)

               (use 'docker port' to see the actual mapping)

--link=""  : Add link to another container (<name or id>:alias or <name or id>)

参考:https ://docs.docker.com/engine/reference/run/#expose-incoming-ports


推荐阅读