Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active May 13, 2024 09:40
Show Gist options
  • Save pulkitsinghal/c1b40aa9acb2881505f26eb6992fb794 to your computer and use it in GitHub Desktop.
Save pulkitsinghal/c1b40aa9acb2881505f26eb6992fb794 to your computer and use it in GitHub Desktop.
How can a nodejs process running inside a docker container, get that container's id?

Problem

How can a nodejs process running inside a docker container, get that container's id?

Solution

the hostname seems to be the short container id in Docker v1.12

It works and this idea was found in this SO post.

// make sure your version on nodejs has the method
// NodeJS v6: https://nodejs.org/dist/latest-v6.x/docs/api/os.html

const os = require('os');
console.log( os.hostname() );

Motivation

I wanted my worker container to run once and then die. Docker policy like restart:always could then start a new one and this way I would ensure that mistakes in code would never cause data to leak from one job run to another. The memory space should be entirely sanitized/separate when the container is restarted.

But the way container logs were being colored and spit out on my console, made it seem like one worker run was handling multiple jobs before shutting down sometimes. This was supicious so I wanted to use container_id to make sure that the log coloring wasn't throwing me off. Ultimately, this idea was no good because the same container_id is used across restarts so this wasn't a good way for me to debug or ascertain anything :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment