This question follows from this (closed/redirected) question: express app server . listen all interfaces instead of localhost only
From that post, I now understand that the following code listens to port 3000 on all interfaces:
// helpers.mjs
const connectToDatabase = () => {
const dummyPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
return dummyPromise;
};
export default connectToDatabase;
// app.mjs
import express from 'express';
import connectToDatabase from './helpers.mjs'
const app = express();
app.get('/', (req, res) => {
res.send('<h2>Hi there!</h2>');
});
await connectToDatabase();
app.listen(3000);
I'm trying to fill in a big gap in my understanding on the relationship between IP addresses and ports. From this question, I learned a little about how an IP address is assigned to an interface. Further, I infer that an IP address has multiple ports (is it more correct for me to say "an interface has multiple ports"?).
My question is: as a webserver author, why would/should I bind to/listen at a specific port on every IP address as opposed to a that same port at one specific IP address?
E.g. the above code is a simple webserver that listens at 127.0.0.1:3000, 127.0.0.2:3000, 127.0.0.3:3000, etc.
Why is that desirable/convention/best practice? As opposed to listening specifically and only 127.0.0.14:3000?
Is this just that individual webserver developer's choice? Or is there a prevailing convention why you should listen to a specific port at every available IP address?
Like, the fact that host is an optional argument implies that there's a legit use-case where you'd want to listen at 127.0.0.1:3000, and 127.0.0.2:3000, and every other available ip_address:3000 -- why is that?