Simone Masiero
Simone Masiero

Reputation: 313

Get host ip from docker in Node.js

I'm trying to retrieve the host IP using node.js running inside a Docker container.

I'm making some test and I'm using this npm package.

It seems working but I have the two following problems:

My node app is the following:

dockerhost = require(`get-docker-host`),
isInDocker = require(`is-in-docker`),

function dockerHost() {
    dockerhost(async (error, result) => {
        if (result) {
            console.log(result);
            return await result;
        } else if (error) {
            console.log(error);
            return await error;
        }
    })
}


if(isInDocker()) {
    console.log("My Docker host is " + dockerHost());
}

Upvotes: 1

Views: 4076

Answers (1)

David Maze
David Maze

Reputation: 158647

get-docker-host is asynchronous, in that it takes a callback function and calls it later, but it doesn't return a promise and so I don't think you can call it using async/await syntax. You can't block on it returning; you can put your main application behind a callback, or manually wrap it in a promise. There are some examples in the MDN async/await documentation.

Here's a working example that wraps the get-docker-host result in a promise. If it's not in Docker then the promise resolves with a null address; if it is, and get-docker-host succeeds, it resolves with the host address, and if not, it fails with the corresponding error.

index.js:

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('Docker host is ' + addr);
    } else {
        console.log('Not in Docker');
    }
}).catch((error) => {
    console.log('Could not find Docker host: ' + error);
});

Dockerfile:

FROM node:10
COPY package.json yarn.lock ./
RUN yarn install
COPY index.js ./
CMD ["node", "./index.js"]

Running it:

% node index.js
Not in Docker
% docker build .
Sending build context to Docker daemon   21.5kB
...
Successfully built e14d41aa0c9b
% docker run --rm e14d41aa0c9b
Docker host is 172.17.0.1

Upvotes: 3

Related Questions