Port

Term side of the Card.
Topic: Basics
Unit title: Port
Categories: Hardware, Software
Explanation side of the Card

Explanation: The point of connection used to send or receive data. It can be a physical interface like USB or a network port, a number from '0' to '65535' that identifies a service on a host, such as '443' for HTTPS.

Example

Wrongjs
const app = express();
app.listen(3000);
Rightjs
const app = express();
const port = Number(process.env.PORT) || 3000;
app.listen(port, () => console.log(`Listening on ${port}`));

Hosting platforms assign the port through PORT; a hardcoded port can leave the app unreachable there.

Common mistakes

  • The app fails to start with 'EADDRINUSE' because another process already uses the port.
  • The app works locally but is unreachable on the host because it ignores the assigned port.

Key points

  • The server reads its port from an environment variable such as PORT and only falls back to a default.
  • Development servers bind to localhost unless they must be reachable from other machines.
  • Database and admin ports are not exposed to the public internet.

Interview questions

What is the difference between port 80 and 443?

Port 80 is the default for plain HTTP and port 443 is the default for HTTPS.

Why do I need root to use ports below 1024?

On Unix-like systems ports 0 to 1023 are privileged, so binding to them needs extra rights. Use a higher port and put a proxy in front.

How do I find which process is using a port?

On macOS and Linux run lsof -i :3000; on Windows run netstat -ano and look for the port.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy