docker-compose中如果需要配置主機(jī)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
是我在家中網(wǎng)絡(luò)的IP地址,而在公司地址會變化蚓聘,導(dǎo)致需要卸載容器實(shí)例重新配置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