Home > Software design >  I am building container with node. but I can't connect app in container
I am building container with node. but I can't connect app in container

Time:06-12

I am building container with node. I have two type of codes. I think two codes very simple and similar. and package.json and Dockerfile is same. just different code. but I can connect app in container. but the other one can't connect app in container.

This code is working well in container.

const express = require('express')

const PORT = 3000;

const app = express();
app.get('/',(req,res)=>{
    res.send('Hello World');
});

app.listen(PORT);
console.log('Running');

but This code is not working What wrong with this? this is node official sample code.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

please tell me what problem is. Thank you in advance

CodePudding user response:

The sample code works when run on the host machine, but not when run in a container.

The issue is that the sample code binds to the 127.0.0.1 IP address. That means that it'll only accept connections from localhost.

In a container, localhost is the container itself. So when you try to connect from the docker host, it looks like the connection comes from another machine and the connection is rejected.

To fix it, you need to make it accept connections from outside the container. You can do that by changing the hostname variable to 0.0.0.0 like this

const http = require('http');

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

You can also leave out the hostname variable on the server.listen call as you've done in the first program. The default value is 0.0.0.0, so leaving it out also works.

  • Related