os.hostname()

Returns the host name of the operating system as a string.

Signature
os.hostname()
  • Added in Node.js v0.3.3

Return value

stringThe host name of the operating system as a string.

os.hostname() returns the name the operating system has for itself. It performs no DNS lookup and sends no packets — it is a local system call, so it is cheap enough to call on every log line, though caching it at startup is tidier.

When to reach for it

Identifying which machine produced something. Stamp it into structured logs and metrics so you can tell one replica's output from another's, include it in crash reports and health responses, and use it as a tie-breaker or lock owner in a distributed job runner.

What trips people up

In a container it returns the container's hostname, which by default is a truncated container ID and on Kubernetes is the pod name — useful, but not the node the pod runs on. If you want the underlying host you must pass it in through the downward API or an environment variable.

It is also not a resolvable address. The value may be a short name with no domain, or an FQDN, depending on how the machine was configured; nothing guarantees DNS knows about it, and nothing guarantees uniqueness across your fleet. For a network address, enumerate os.networkInterfaces() instead. Hostnames can also change at runtime, so a long-lived process holding a cached value can drift.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Stamp the instance name into every structured log line
  • Report which replica served a request from a /health endpoint
  • Record the lock owner when several workers compete for a scheduled job

Frequently asked questions

Why does os.hostname() return a random string in Docker?

Because Docker sets the container's hostname to a truncated container ID unless you pass --hostname. On Kubernetes the same call returns the pod name. Neither identifies the underlying node, so inject that separately via the downward API if you need it.

Does os.hostname() return the fully qualified domain name?

Not reliably. It returns whatever the system has configured, which may be a short name or an FQDN depending on the host. If you need a resolvable name, do a reverse lookup with dns.reverse() on an address from os.networkInterfaces() rather than assuming the hostname resolves.

Is os.hostname() slow enough to cache?

It is a cheap local system call with no network involved, so calling it per log line is fine. Caching it once at startup is still the common pattern because it keeps the value consistent across a request even if an administrator renames the machine mid-process.

More examples

Stamp the instance into structured logs

Every line now carries the instance and pid, which is what lets you filter one replica out of an aggregated log stream. The env-var override matters in orchestrated environments, where you often want a stable service name rather than a pod name that changes on every restart.

Example · javascript
const os = require('node:os');

// Resolve once at startup; the value does not normally change.
const instance = process.env.INSTANCE_NAME ?? os.hostname();

function log(level, message, fields = {}) {
  console.log(JSON.stringify({
    ts: new Date(0).toISOString(),
    level,
    instance,
    pid: process.pid,
    message,
    ...fields
  }));
}

log('info', 'service started', { port: 8080 });
log('warn', 'slow query', { ms: 812 });

Build a health payload

This is the payload worth returning from /health: the hostname answers "which instance am I talking to" when a load balancer sits in front of several, and the rest gives enough context to spot an odd node without opening a shell on it.

Example · javascript
const os = require('node:os');

function health() {
  return {
    host: os.hostname(),
    platform: `${os.platform()}-${os.arch()}`,
    node: process.versions.node,
    uptimeSec: Math.round(os.uptime()),
    parallelism: os.availableParallelism(),
    memory: {
      totalMB: Math.round(os.totalmem() / 1024 ** 2),
      freeMB: Math.round(os.freemem() / 1024 ** 2)
    }
  };
}

console.log(JSON.stringify(health(), null, 2));

Derive a stable worker identity

The hostname alone collides whenever two processes run on one machine, so appending the pid is the minimum for a usable worker identity. The hash gives a fixed-width id that is safe to put in a database column or a lock key without worrying about hostname length or characters.

Example · javascript
const os = require('node:os');
const crypto = require('node:crypto');

// hostname alone is not unique when several processes share a machine.
const workerId = `${os.hostname()}#${process.pid}`;
const shortId = crypto.createHash('sha256').update(workerId).digest('hex').slice(0, 12);

console.log('worker id:', workerId);
console.log('hashed id:', shortId);
console.log('id is stable within this process:', workerId === `${os.hostname()}#${process.pid}`);

// Whoever holds the lock records this value.
console.log('lock owner record:', { owner: shortId, acquiredAt: 'ISO timestamp' });

Discussion

  • Be the first to comment on this lesson.