docker-compose自定义网络,固定容器ip地址
首先明确两点:
1只有自定义网络,才能手工指定每个容器的ip。默认的bridge是不行的!
2 手工设定了网段比如172.19.0.0 不影响docker在host装的网卡docker0 的172.17.0.1
容器内的172.19.0.XX 还是可以通过172.17.0.1访问到主机。
docker-compose.yml 参考官网 https://docs.docker.com/compose/compose-file/#network-configuration-reference
version: '3.7' services: x1: image: XXX restart: always tty: true networks: mynet1: ipv4_address: 172.19.0.2 networks: mynet1: ipam: config: - subnet: 172.19.0.0/16
说明:
#gateway是网关地址
subnet是网络号段
mynet1是自定义的网络名称
几点说明:
1 2以前,可以在ipam里指定gateway 3以后不许了;
2 静态指定ip,则每个容器都要静态指定,添加networks 部分
3 运行docker-compose up 首先会创建network 注意之前如果已经运行过多个不同工程的docker-compose 可能已经自动创建了很多network
这样如果IP网段已经分配过了,就会失败:
ERROR: Pool overlaps with other one on this address space
类似地,此外如果已经创建了network mynet1的网段 为 172.28.0.0,但是想改成172.19.0.1,也会说失败
这样都需要清理一下无效的network
清除各种不用的docker相关东西 参考 https://blog.csdn.net/wennuanddianbo/article/details/78453325
docker network prune
4 3以后无法指定IP地址类型。只能是ipV6,在node里
const requestIp = require('request-ip'); ... app.use(requestIp.mw()) ... req.clientIp
docker-compose ps
docker-compose -f docker-compose.yml down
version: '3.6'
services:
mysql:
image: harbor.xjgreat.com:8084/davinci/mysql:1.0
restart: always
environment:
- MYSQL_ROOT_PASSWORD=abc123123
- MYSQL_DATABASE=davinci
ports:
- 63306:3306
volumes:
- mysql_data:/var/lib/mysql
- davinci_initdb:/docker-entrypoint-initdb.d:ro
networks:
mynet1:
ipv4_address: 192.1.0.2
davinci:
environment:
- MYSQL_CONN=jdbc:mysql://mysql:3306/davinci?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
- DB_USER=root
- DB_PWD=abc123123
- MAIL_HOST=smtp.exmail.qq.com
- MAIL_PORT=465
- MAIL_STMP_SSL=true
- MAIL_USER=pingtaiceshi@xjgreat.com
- MAIL_PWD=Platform123
- MAIL_NICKNAME=davinci
image: "harbor.xjgreat.com:8084/davinci/davinci:1.0"
ports:
- 8083:8080
command: ["./bin/start.sh", "mysql:3306", "--", "start-server.sh"]
restart: always
volumes:
- davinci_logs:/opt/davinci/logs
- davinci_userfiles:/opt/davinci/userfiles
- davinci_initdb:/initdb
networks:
mynet1:
ipv4_address: 192.1.0.3
davinci_skin:
environment:
- MYSQL_CONN=jdbc:mysql://mysql:3306/davinci_skin?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
- DB_USER=root
- DB_PWD=abc123123
image: "harbor.xjgreat.com:8084/davinci/davinci_skin:1.0"
ports:
- 8082:8080
restart: always
networks:
mynet1:
ipv4_address: 192.1.0.4
networks:
mynet1:
ipam:
config:
- subnet: 192.1.0.0/16
volumes:
davinci_userfiles:
davinci_logs:
davinci_initdb:
mysql_data:
docker-compose -f docker-compose.yml config
docker-compose -f docker-compose.yml up -d -t 120
docker-compose ps