docker-compose 配置IP、hostname、hosts配置
配置IP
version: "3"
networks:bd-network: # 声明网络external: true
services:kafka: # 服务名称networks:bd-network: # 连接的网络名称ipv4_address: 172.2.0.102 # 配置IP
配置 主机名
version: "3"
services:kafka: # 服务名称hostname: kf # 主机名
配置hosts
下面的配置可以修改/etc/hosts文件: 追加zk 172.2.0.101
、kf 172.2.0.102
version: "3"
services:kafka:extra_hosts:- "zk:172.2.0.101"- "kf:172.2.0.102"
配置完成进入容器,可查看验证
$ sudo docker exec -it zk-singleton /bin/bash
$ cat /etc/hosts
完整例子
- 创建一个网络
$ sudo docker network create --driver=bridge --gateway=172.2.0.1 --subnet=172.2.0.0/16 bd-network
- 配置 单节点kafka、zookeeper,kafka通过主机名 访问zookeeper
version: "3"
networks: #声明网络bd-network:external: true
services:zookeeper: # 服务名image: 'bitnami/zookeeper:latest' # 镜像container_name: zk-singleton # 容器名hostname: zk # 主机名networks:bd-network:ipv4_address: 172.2.0.101 # 定义容器ipextra_hosts:- "zk:172.2.0.101"- "kf:172.2.0.102"ports: # 宿主端口:容器端口映射- '2181:2181'environment: # 容器环境配置- ALLOW_ANONYMOUS_LOGIN=yes kafka:image: 'bitnami/kafka:latest'container_name: kf-singletonhostname: kfnetworks:bd-network:ipv4_address: 172.2.0.102extra_hosts:- "zk:172.2.0.101"- "kf:172.2.0.102"ports:- '9192:9092'environment:- KAFKA_BROKER_ID=1- ALLOW_PLAINTEXT_LISTENER=yes- KAFKA_CFG_LISTENERS=PLAINTEXT://:9092- KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://:9092- KAFKA_CFG_ZOOKEEPER_CONNECT=zk:2181 # 通过主机名访问zookeeperdepends_on: # 依赖- zookeeper
3 验证
$ sudo docker exec -it kf-singleton /bin/bash
$ hostname
$ cat /etc/hosts