1

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:

  • I have to find a way to let the function waits for the response (seems not working with async/await)
  • I don't know if it will behave correctly using docker swarm.

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());
}

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

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.