1. 程式人生 > >Docker學習筆記:Docker 埠對映

Docker學習筆記:Docker 埠對映

# Find IP address of container with ID <container_id> 通過容器 id 獲取 ip $ sudo docker inspect <container_id> | grep IPAddress | cut -d ’"’ -f 4

無論如何,這些 ip 是基於本地系統的並且容器的埠非本地主機是訪問不到的。此外,除了埠只能本地訪問外,對於容器的另外一個問題是這些 ip 在容器每次啟動的時候都會改變。

Docker 解決了容器的這兩個問題,並且給容器內部服務的訪問提供了一個簡單而可靠的方法。Docker 通過埠繫結主機系統的介面,允許非本地客戶端訪問容器內部執行的服務。為了簡便的使得容器間通訊,Docker 提供了這種連線機制。

5.1 自動對映埠

-P使用時需要指定--expose選項,指定需要對外提供服務的埠

$ sudo docker run -t -P --expose 22 --name server  ubuntu:14.04

使用docker run -P自動繫結所有對外提供服務的容器埠,對映的埠將會從沒有使用的埠池中 (49000..49900) 自動選擇,你可以通過docker ps、docker inspect <container_id>或者docker port <container_id> <port>確定具體的繫結資訊。

5.2 繫結埠到指定介面

基本語法

$ sudo docker run -p [([<host_interface>:[host_port]])|(<host_port>):]<container_port>[/udp] <image> <cmd>

預設不指定繫結 ip 則監聽所有網路介面。

 繫結 TCP 埠

# Bind TCP port 8080 of the container to TCP port 80 on 127.0.0.1 of the host machine. $ sudo docker run -p 127.0.0.1:80:8080 <image> <cmd> # Bind TCP port 8080 of the container to a dynamically allocated TCP port on 127.0.0.1 of the host machine. $ sudo docker run -p 127.0.0.1::8080 <image> <cmd> # Bind TCP port 8080 of the container to TCP port 80 on all available interfaces of the host machine. $ sudo docker run -p 80:8080 <image> <cmd> # Bind TCP port 8080 of the container to a dynamically allocated TCP port on all available interfaces $ sudo docker run -p 8080 <image> <cmd>

繫結 UDP 埠

# Bind UDP port 5353 of the container to UDP port 53 on 127.0.0.1 of the host machine. $ sudo docker run -p 127.0.0.1:53:5353/udp <image> <cmd>