Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the IP address of the docker host from inside a docker container

Tags:

docker

ip

As the title says. I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.

like image 323
xiamx Avatar asked Apr 08 '14 17:04

xiamx


People also ask

How do I get container IP inside container?

You can easily get the IP address of any container if you have the name or ID of the container. You can get the container names using the "Docker ps -a" command. This will list all the existing containers.

How does Docker container get IP address?

By default, the container is assigned an IP address for every Docker network it connects to. The IP address is assigned from the pool assigned to the network, so the Docker daemon effectively acts as a DHCP server for each container. Each network also has a default subnet mask and gateway.

What is the default IP address of the Docker host?

Usually Docker uses the default 172.17. 0.0/16 subnet for container networking.


2 Answers

/sbin/ip route|awk '/default/ { print $3 }' 

As @MichaelNeale noticed, there is no sense to use this method in Dockerfile (except when we need this IP during build time only), because this IP will be hardcoded during build time.

like image 107
spinus Avatar answered Sep 17 '22 23:09

spinus


As of version 18.03, you can use host.docker.internal as the host's IP.

Works in Docker for Mac, Docker for Windows, and perhaps other platforms as well.

This is an update from the Mac-specific docker.for.mac.localhost, available since version 17.06, and docker.for.mac.host.internal, available since version 17.12, which may also still work on that platform.

Note, as in the Mac and Windows documentation, this is for development purposes only.

For example, I have environment variables set on my host:

MONGO_SERVER=host.docker.internal 

In my docker-compose.yml file, I have this:

version: '3'  services:   api:     build: ./api     volumes:       - ./api:/usr/src/app:ro     ports:       - "8000"     environment:       - MONGO_SERVER     command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi 
like image 27
aljabear Avatar answered Sep 19 '22 23:09

aljabear