在 Docker Compose 中,可以使用 networks 配置项快速且方便地创建自定义网络。
version: '3' services: # 定义mysql服务 mysql: image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 12345678 MYSQL_DATABASE: demo_db volumes: - /var/data/mysql:/var/lib/mysql networks: # 加入到自定义的mynetwork网络中,看这里 - mynetwork # 定义nginx服务 nginx: image: nginx:latest ports: - "8080:80" depends_on: - mysql volumes: - /var/data/nginx_config:/etc/nginx/conf.d - myvolume:/usr/share/nginx/html networks: # 加入到自定义的mynetwork网络中,看这里 - mynetwork # 自定义网络,看这里 networks: mynetwork: driver: bridge volumes: myvolume:
上面例子中,首先定义了一个名为 mynetwork 的网络,其驱动类型为 bridge。然后,mysql 和 nginx 服务都加入到自定义的 mynetwork 网络。
在包含上述docker-compose.yml文件的目录中,运行以下命令启动应用:
// 启动容器 root@hxstrive:~# docker-compose up -d Creating network "root_mynetwork" with driver "bridge" Creating root_mysql_1 ... done Creating root_nginx_1 ... done
可以使用以下命令查看创建的网络:
// 查看网络列表 root@hxstrive:~# docker network ls NETWORK ID NAME DRIVER SCOPE ac700a39ff94 bridge bridge local 23f832eeba6e host host local 750730ce4667 mynetwork bridge local f83cddfed9c2 none null local efb10cc5a121 root_default bridge local 98c408eab28b root_mynetwork bridge local 这就是刚创建的网络
上面将列出所有的 Docker 网络,包括自定义网络 “mynetwork”。
注意,上面名为“root_mynetwork”的网络就是我们定义的“mynetwork”网络,其中“root”是用户名,由 docker compose 自动拼接上去的,用于避免网络名称冲突。
执行 docker network inspect 查看 root_mynetwork 网络详细信息:
root@hxstrive:~# docker network inspect root_mynetwork [ { "Name": "root_mynetwork", "Id": "98c408eab28bca735535621aeffb8739c742d37b380be766f572110f344e43c9", "Created": "2024-09-10T15:16:20.124885499+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.18.0.0/16", "Gateway": "172.18.0.1" } ] }, "Internal": false, "Attachable": true, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, // 该网络中包含两个容器 "Containers": { "1ae23e52517815af471e7fd643d320a8cdbbe97fc278fa4f6c548d8bab236fb2": { "Name": "root_mysql_1", "EndpointID": "f82636a24625bf91d8ee08facec158487ce95f087893ea2a814988f4ccc2e2e1", "MacAddress": "02:42:ac:12:00:02", "IPv4Address": "172.18.0.2/16", "IPv6Address": "" }, "31406648dcae589264ee8b5e0168acd4661868224ae6a7c486dddb8b2241345d": { "Name": "root_nginx_1", "EndpointID": "e3a8198de46483b4715941039f9cb3e85c4317d7678ed905d6554c41f75702f1", "MacAddress": "02:42:ac:12:00:03", "IPv4Address": "172.18.0.3/16", "IPv6Address": "" } }, "Options": {}, "Labels": { "com.docker.compose.network": "mynetwork", "com.docker.compose.project": "root", "com.docker.compose.version": "1.29.2" } } ]
注意,通过创建自定义网络,可以更好地组织和管理容器之间的通信,提高应用程序的可扩展性和可维护性。