关注微信公众号,可查看本文的视频演示:
上一篇文章:最简单的Yii环境搭建方法
1、背景
由于在docker-compose编排容器的时候,Yii官方提供的docker-compose.yml文件并没有使用自定义网络,因此每次重启电脑或者重启容器组的时候,各个容器的IP都会发生变化,导致频繁修改配置文件,非常麻烦。
2、问题演示
以Mysql为例,每次重启容器组的时候,mysql容器IP是会发生变化的:
chenzhiwei:advanced$ docker inspect advanced_mysql_1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.22.0.3",
chenzhiwei:advanced$ sudo docker-compose stop
Stopping advanced_backend_1 ... done
Stopping advanced_mysql_1 ... done
Stopping advanced_frontend_1 ... done
chenzhiwei:advanced$ sudo docker-compose start
Starting frontend ... done
Starting backend ... done
Starting mysql ... done
chenzhiwei:advanced$ docker inspect advanced_mysql_1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.22.0.2",
chenzhiwei:advanced$
由上演示可知,容器组重新启动后,Mysql容器的IP由172.22.0.3
变为了172.22.0.2
,同理,frontend和backend容器的IP都会随机变化。
3、自定义网络配置
注意:在修改配置文件前,需要卸载当前的容器编排,否则docker-compose是无法按照修改后的网络删除已编排的容器网络配置的,这会导致当前ip段不可用。
卸载当前的容器编排命令如下:
sudo docker-compose down
加入静态IP配置的配置文件如下:
version: '3.2'
services:
frontend:
build: frontend
ports:
- 20080:80
volumes:
# Re-use local composer cache via host-volume
- ~/.composer-docker/cache:/root/.composer/cache:delegated
# Mount source-code for development
- ./:/app
networks:
extnetwork:
ipv4_address: 172.22.0.4
backend:
build: backend
ports:
- 21080:80
volumes:
# Re-use local composer cache via host-volume
- ~/.composer-docker/cache:/root/.composer/cache:delegated
# Mount source-code for development
- ./:/app
networks:
extnetwork:
ipv4_address: 172.22.0.3
mysql:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=verysecret
- MYSQL_DATABASE=yii2advanced
- MYSQL_USER=yii2advanced
- MYSQL_PASSWORD=secret
networks:
extnetwork:
ipv4_address: 172.22.0.2
networks:
extnetwork:
ipam:
config:
- subnet: 172.22.0.0/16
gateway: 172.22.0.1
重新编排命令如下:
chenzhiwei:advanced$ sudo docker-compose up -d
Creating network "advanced_extnetwork" with the default driver
Creating advanced_backend_1 ... done
Creating advanced_mysql_1 ... done
Creating advanced_frontend_1 ... done
chenzhiwei:advanced$ docker inspect advanced_mysql_1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.22.0.2",
chenzhiwei:advanced$