docker-compose自动识别主机IP

docker-compose中如果需要配置主机IP,很多是用硬编码的方式:

version: '3'
services:
  zookeeper:
    image: zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka
    depends_on: [ zookeeper ]
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_HOST_NAME: 192.168.50.149
      KAFKA_CREATE_TOPICS: "test:1:1"
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - ~/dockercompose/kafka/docker.sock:/var/run/docker.sock
  kafka-manager:
    image: sheepkiller/kafka-manager
    command: -Dpidfile.path=/dev/null
    depends_on:
      - zookeeper
      - kafka
    ports:
      - "9000:9000"
    environment:
      ZK_HOSTS: zookeeper:2181

其中的192.168.50.149是我在家中网络的IP地址,而在公司地址会变化,导致需要卸载容器实例重新配置IP再启动。

mac和win

直接使用 host.docker.internal

version: '3'
services:
  zookeeper:
    image: zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka
    depends_on: [ zookeeper ]
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_HOST_NAME: host.docker.internal
      KAFKA_CREATE_TOPICS: "test:1:1"
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - ~/dockercompose/kafka/docker.sock:/var/run/docker.sock
  kafka-manager:
    image: sheepkiller/kafka-manager
    command: -Dpidfile.path=/dev/null
    depends_on:
      - zookeeper
      - kafka
    ports:
      - "9000:9000"
    environment:
      ZK_HOSTS: zookeeper:2181

但是要注意的是,这是Docker Desktop 18.03+所支持的

linux

Docker Engine users on Linux can enable host.docker.internal too via the --add-host flag for docker run. Start your containers with this flag to expose the host string:

docker run -d --add-host host.docker.internal:host-gateway my-container:latest

The --add-host flag adds an entry to the container’s /etc/hosts file. The value shown above maps host.docker.internal to the container’s host gateway, which matches the real localhost value. You could replace host.docker.internal with your own string if you prefer.

其他方式

通过network直接连接host,也可以配置成bridge

你可能感兴趣的:(docker-compose自动识别主机IP)