0

I am trying to get a docker container's Id when network=host settings is enabled but instead of getting the containerId I am getting the host instance name. But, in case my network=host is not passed in the command it gives me the containerId as expected. In short:

Case 1- I run my container with command – docker run --network="host" -d -it myservice:1.0

const os = require("os");
console.log(os.hostname()) /// prints **docker-desktop**

Case 2- I run my container with command – docker run -d -it myservice:1.0

const os = require("os");
console.log(os.hostname()) /// prints **67db4w32k112** as expected

Is there a way I can get the same output i.e 67db4w32k112 in case 1 as well?

Neo Anderson
  • 5,957
  • 2
  • 12
  • 29
Lavish
  • 11
  • 4
  • Why do you need the container ID? Why do you need host networking? Needing either of these is a little bit unusual, so if you could for example avoid needing host networking then the `hostname()` call you describe would work. – David Maze Mar 09 '20 at 20:57

2 Answers2

1

From looking at this thread you can probably do something like below which will read the /proc/1/cpuset file inside the container. This file has the current container ID, the contents look like:

/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605

This will be more reliable in your case than using os.hostname() since it works both with and without the --newtwork="host"flag on the docker run command.

fs = require('fs')
fs.readFile('/proc/1/cpuset', 'utf8', function(err, data) {
  if (err) {
    return console.log(err);
  }
  let containerID = data.replace("/docker/", "");
  console.log(containerID);
});
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
  • Is there a way we can use without worrying about infrastructure. Like something that gives instanceId in case it is deployed over the normal ec2-instance, gives dockerId if deployed as docker containers? – Lavish Mar 10 '20 at 05:49
  • @Lavish I do not know much about ec2-instances, might be worth it to research / ask another question about that. – Andrew Lohr Mar 10 '20 at 15:11
0

Try to use a helper package such as docker-container-id

Add the dependency in your package.json

npm install --save docker-container-id

Here's an example:

const getId = require('docker-container-id');

async function() {
  console.log("I'm in container:", await getId());
}

npmjs reference

Neo Anderson
  • 5,957
  • 2
  • 12
  • 29