0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'm really confused on this. I've logged into the container and see in my /etc/hosts file with an entry of "-e host.docker.internal". I can't seem to echo out the value and it does not resolve. How do I get this from NodeJS? I am using the "os" dependency and then doing "var hostname = os.hostname()". Do I need to map this somehow?
I'm not 100% sure I interpreted your original question correctly, maybe this isn't exactly what you're looking for. But my thought was that rather than getting the host IP, you can simply use host.docker.internal in place of the IP wherever you need to communicate with the host, removing the need for any sort of getDockerHost library or function.
That did it! You can actually ping that on inside of the container and it will resolve to the host IP. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.