docker-compose 网络配置- IP 主机名 hosts配置

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.101kf 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
完整例子
  1. 创建一个网络
$ sudo docker network create --driver=bridge --gateway=172.2.0.1 --subnet=172.2.0.0/16  bd-network
  1. 配置 单节点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   # 定义容器ip
        extra_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-singleton
        hostname: kf
        networks:
            bd-network:
                ipv4_address: 172.2.0.102
        extra_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           # 通过主机名访问zookeeper
        depends_on:                         # 依赖
          - zookeeper

3 验证

$ sudo docker exec -it kf-singleton /bin/bash
$ hostname
$ cat /etc/hosts

docker-compose 网络配置- IP 主机名 hosts配置_第1张图片

你可能感兴趣的:(docker,docker,docker-compose,网络配置,ip,主机名,hosts)