简体   繁体   中英

Docker Compose Set Linux Docker Host IP Address in Container's /etc/hosts

When using Docker Compose, how can we determine and set the IP address of the Docker host in the /etc/hosts file of the Docker container when the host is running Linux? I will like a hostname like DOCKER_HOST in the container to refer to the Docker host.

Docker for Linux does not yet support host.docker.internal , unlike Docker for Windows and Docker for Mac, so we need an alternative to this.

--network host cannot be used here because for my purpose localhost in the container must still refer to the container itself.

Docker Compose supports using extra_hosts to add a hostname-ip mapping in /etc/hosts , but I am unable to figure out how to automatically determine the host IP address to be used.

version: '3'
services:
    api:
        build: .
        ports:
            - "8080:8080"
        extra_hosts:
            - "DOCKER_HOST:X.X.X.X"   # <=== How do we automatically set this IP address?

Is it possible to do something like the following, where we do not have to manually define the Docker host IP address when starting the containers?

DOCKER_HOST=`command_to_get_host_ip` docker-compose up -d 

Or can we set a static IP for the Docker host in docker-compose.yml ?

You can try:

DOCKER_HOST=$(python -c 'import socket;print(socket.gethostbyname(socket.gethostname()))') docker-compose up -d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM