zhaoyu@home:~$

网络

默认情况下,Docker拥有三个networks,每个网络拥有不同的driver,通过如下命令显示网络。 ```shell script docker network ls

结果如下:

NETWORK ID NAME DRIVER SCOPE 6c4e27ea27ed bridge bridge local c85058ab38c7 host host local 5dcfd419f500 none null local

### 创建自定义的桥接网络
创建一个自定义的桥接网络命令如下:

docker network create –driver bridge –label project=dockerinaction –label chapter=5
–attachable –scope local –subnet 10.0.42.0/24 –ip-range 10.0.42.128/25 user-network

`--ip-range 10.0.42.128/25`表示使用该网络的容器ip范围为`10.0.42.128`到`10.0.42.255`。

接着我们添加一个容器到该网络。
```shell script
docker run -it --network user-network --name network-explorer alpine:latest sh

运行上述命令后,进入命令输如

host 和 none网络

当在创建容器时指定 --network host,那么就是告诉容器,网络不创建自己的network namespace。共享了宿主机的network namespace。 创建一个host网络如下: ```shell script docker run -d –name test –network host hub.c.163.com/library/busybox:latest /bin/sh -c “while true;do sleep 3600;done”

进入容器查看网络:
```shell script
docker exec -it test ip -4 -o a

可以看到容器的网络和宿主机网络一样。

网络指定为--network none,将容器设置为无网络。创建命令如下: ```shell script docker run -d –name test1 –network none hub.c.163.com/library/busybox:latest /bin/sh -c “while true;do sleep 3600;done”

进入容器查看网络:
```shell script
docker exec -it test1 ip -4 -o a

可以看到容器test1没有网络设置。

网络端口映射

将临时的TCP请求映射到容器TCP8080端口: ```shell script docker run –rm -p 8080 alpine:latest echo “forward ephemeral TCP -> container TCP 8080”

将主机的UDP8080端口映射到容器的UDP8888端口:
```shell script
docker run --rm -p 8080:8888/udp alpine:latest echo "host UDP 8088 -> container UDP 8080"

映射多个tcp端口: ```shell script docker run –rm -p 127.0.0.1:8080:8080/tcp -p 127.0.0.1:3000:3000/tcp alpine:latest echo “forward multiple TCP ports.”

查看容器wp3端口80对应的主机端口:
```shell script
docker port wp3 80

DNS配置

设置容器的主机名: ```shell script docker run –rm –hostname barker alpine:latest echo “hostname.”

设置dns:
```shell script
docker run -rm --dns 8.8.8.8 alpine:latest echo "dns."

设置主机名和ip的映射。 ```shell script docker run –name addhost –rm –add-host test:10.10.10.255 alpine:latest echo “add-host.”

使用nslookup 工具反查test的ip。
```shell script
docker exec -it test nslookup test