docker network自定义网络

问题

docker-compose启动自动创建网络,在云上会出现子网冲突导致路由失效。

env

  • docker
  • docker-compose

解决

1.network参数

mvpbang@mvpbang ~ % docker network -h
Flag shorthand -h has been deprecated, use --help
Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.
mvpbang@mvpbang ~ % 
mvpbang@mvpbang ~ % docker network create -h
Flag shorthand -h has been deprecated, use --help
Usage:  docker network create [OPTIONS] NETWORK

Create a network

Options:
      --attachable           Enable manual container attachment
      --aux-address map      Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
      --config-from string   The network from which to copy the configuration
      --config-only          Create a configuration only network
  -d, --driver string        Driver to manage the Network (default "bridge")
      --gateway strings      IPv4 or IPv6 Gateway for the master subnet
      --ingress              Create swarm routing-mesh network
      --internal             Restrict external access to the network
      --ip-range strings     Allocate container ip from a sub-range
      --ipam-driver string   IP Address Management Driver (default "default")
      --ipam-opt map         Set IPAM driver specific options (default map[])
      --ipv4                 Enable or disable IPv4 address assignment (default true)
      --ipv6                 Enable or disable IPv6 address assignment
      --label list           Set metadata on a network
  -o, --opt map              Set driver specific options (default map[])
      --scope string         Control the network's scope

2.查看宿主机网络段

 docker inspect $(docker network ls -q) |grep Subnet
                    "Subnet": "172.19.0.0/16",
                    "Subnet": "172.17.0.0/16",
                    "Subnet": "172.28.0.0/16",
                    "Subnet": "172.20.0.0/16",

3.新建自定义网络

docker network create -d bridge  --subnet 172.18.1.0/24 --gateway 172.18.1.254  ocrnet

4.docker-compose.yml使用已存在网络

1
2
3
4
5
6
...
networks:
- ocrnet
networks:
ocrnet:
external: true # 使用外部网络