Docker Compose 网络配置实验背景
本次实验记录了 Docker 环境下的网络配置流程,旨在整理操作细节以备后续查阅。
测试环境基于 Centos 7.4 系统,使用的 Docker 版本为 18.03.1-ce,Docker Compose 版本为 1.18.0。
cat docker-compose.yml
version: '3'
services:
test1:
image: busybox:latest # 镜像为 busybox
entrypoint: # 容器启动后执行 top 命令,使容器没法立即退出
- top
networks:
backend: # 使用指定的网络 backend, 并且设置网络别名为 test1,
aliases: # 设置网络别名后,可以在其他容器中 ping test1 访问到该容器
- test1
test2:
image: busybox:latest
entrypoint:
- top
networks:
backend:
aliases:
- test2
networks:
backend:
启动配置
docker-compose up -d
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4d05ceb2088d busybox:latest "top" 5 seconds ago Up 4 seconds ibaboss_test2_1
f4ccafa24664 busybox:latest "top" 5 seconds ago Up 4 seconds ibaboss_test1_1
docker exec -it 4d05ceb2088d /bin/sh
/ # ping test1
PING test1 (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: seq=0 ttl=64 time=0.061 ms
64 bytes from 172.19.0.2: seq=1 ttl=64 time=0.062 ms
ping ibaboss_test1_1
PING ibaboss_test1_1 (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: seq=0 ttl=64 time=0.045 ms
64 bytes from 172.19.0.2: seq=1 ttl=64 time=0.056 ms
64 bytes from 172.19.0.2: seq=2 ttl=64 time=0.061 ms
# 在网络中可以通过 容器名字或者网络的别名 进行通信
Compose 生成的容器默认遵循特定命名规范,格式通常为:<项目名称><服务名称><序号>。
尽管允许自定义项目名称和服务名称,但若需完全掌控容器的命名规则,可通过指定标签来实现。
container_name: app
cat docker-compose_v1.yml
version: '3'
services:
test1:
image: busybox:latest
entrypoint:
- top
container_name: test1
networks:
- backend
test2:
image: busybox:latest
entrypoint:
- top
container_name: test2
networks:
- backend
networks:
backend:
执行启动命令
docker-compose -f docker-compose_v1.yml up -d
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
132859fc77c2 busybox:latest "top" About a minute ago Up About a minute test2
cd0a78dc9bd4 busybox:latest "top" About a minute ago Up About a minute test1
docker exec -it 132859fc77c2 ping test1
PING test1 (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: seq=0 ttl=64 time=0.070 ms
64 bytes from 172.19.0.2: seq=1 ttl=64 time=0.068 ms
64 bytes from 172.19.0.2: seq=2 ttl=64 time=0.059 ms
补充说明
Docker Compose 多容器共用网络场景
此前计划利用 Docker Compose 构建多容器共享同一网络环境的架构,但多次尝试均报错。经排查发现,错误源于端口绑定位置不当:端口仅能绑定在负责生成网卡的容器上,若绑定在其他容器则会引发故障。例如,当 MySQL 服务复用 Nginx 的网络接口并在 MySQL 配置中声明 port:3306 时,运行将失败;而将 3306 端口映射移至 Nginx 侧则能成功启动。
version: '3.3'
services:
nginx:
image: "lnp_php"
# container_name: "lnmp_nginx"
ports:
- "80:80"
- "443:443"
- "3306:3306"
expose:
- "3306"
volumes:
- /home/www/php:/home/www:rw
# depends_on:
# - mysql
# links:
# - mysql
mysql:
image: "mysql"
# container_name: "lnmp_mysql"
# ports:
# - "3306:3306"
# expose:
# - "3306"
volumes:
- /home/docker/conf/mysql_w:/etc/mysql:rw
environment:
- MYSQL_ROOT_PASSWORD=123456
depends_on:
- nginx
network_mode: "service:nginx"
以上内容为本次技术记录的总结,期望能为读者的学习提供便利,同时也欢迎继续支持本站。