Skip to content

Commit 000a10b

Browse files
host utils
1 parent 807950d commit 000a10b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lib/utils/host.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const isDocker = (() => {
2+
let isDocker;
3+
4+
const hostname = require('os').hostname();
5+
const pattern = new RegExp(
6+
'[0-9]+\:[a-z_-]+\:\/docker\/' + hostname + '[0-9a-z]+', 'i'
7+
);
8+
9+
try {
10+
isDocker = require('child_process')
11+
.execSync(
12+
'cat /proc/self/cgroup',
13+
{stdio: ['ignore', 'pipe', 'ignore']}
14+
)
15+
.toString().match(pattern) !== null;
16+
} catch (e) {
17+
isDocker = false;
18+
}
19+
20+
return isDocker;
21+
})();
22+
23+
const defaultHost = isDocker ? '0.0.0.0' : 'localhost';
24+
25+
// when we're runing in Docker, we can expect (generally, in a development
26+
// scenario) that the user would like to connect to the service in the
27+
// container via the **host's** loopback address, so this helper can be used to
28+
// swap 0.0.0.0 for localhost in code/messages that pertain to client-side
29+
function canonicalHost(host) {
30+
return isDocker && host === '0.0.0.0' ? 'localhost' : host;
31+
}
32+
33+
function dockerHostSwap(host) {
34+
return (isDocker && (host === 'localhost' || host === '127.0.0.1')) ? defaultHost : host;
35+
}
36+
37+
const defaultCorsHost = canonicalHost(defaultHost);
38+
39+
module.exports = {
40+
canonicalHost,
41+
defaultCorsHost,
42+
defaultHost,
43+
dockerHostSwap,
44+
isDocker
45+
};

0 commit comments

Comments
 (0)