Kevin
Kevin

Reputation: 2888

Getting Docker Host IP via NodeJS

I am writing a NodeJS Application in which I am trying to get the docker host IP from inside the docker container however; the node APIs I am using get only seem to get the docker container IP..

The first method I am using the os API:

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log("os.gethostname API reports as: " +add);
})

os.gethostname API reports as: 172.17.0.2

I also tried

getDockerHost = require('get-docker-host');
isInDocker = require('is-in-docker');

checkDocker = () => {
    return new Promise((resolve, reject) => {
        if (isInDocker()) {
            getDockerHost((error, result) => {
                if (result) {
                    resolve(result);
                } else {
                    reject(error);
                }
            });
        } else {
            resolve(null);
        }
    });
};

checkDocker().then((addr) => {
    if (addr) {
        console.log("'get-docker-host'API' IP reports as: " + addr);
             console.log("END");
    } else {
        console.log('Not in Docker');
    }
}).catch((error) => {
    console.log('Could not find Docker host: ' + error);
});

'get-docker-host'API' IP reports as: 172.17.0.1

When I get the IP of my machine through Bash I get this..

sh-3.2# ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
10.106.117.79

So node API calls must be getting the docker container IP. Is there a way to get the host IP?

Upvotes: 0

Views: 3088

Answers (1)

mkasberg
mkasberg

Reputation: 17262

Use the host.docker.internal hostname, which will resolve to the IP of the host machine that is running the container.

Upvotes: 2

Related Questions