Key idea
An IP address gets a packet to the right machine. A port, a number from 1 to 65535, gets it to the right program on that machine. A program listens on a port, and only one program can listen on the same address and port at a time.
An address, its ports, and who can reach them
The database port answers only on the private network.
Who can reach your app
This lesson is the left half of the diagram. The right half is the next lesson.
Ports you'll meet
A few numbers are conventions everyone follows:
- 443 for HTTPS and 80 for plain HTTP.
- 22 for SSH, to log in to a server.
- 5432 for PostgreSQL, 3306 for MySQL, 6379 for Redis.
- 3000, 5000, 8000 and 8080 for apps in development. Nothing reserves these; frameworks just picked them.
The port in a URL
https://example.com has no port written in it, because the scheme implies one: https means 443, http means 80. When an app uses any other port, the URL has to say so, as in http://localhost:3000.
Your side of the connection gets a port too. The operating system picks a random high number for each connection, so replies find their way back to the right browser tab.
"Address already in use"
Start a second copy of your app and it fails with an error like EADDRINUSE or address already in use. Something is already listening on that port, often a copy you forgot to stop.
Try it: see what's listening on your machine.
lsof -nP -iTCP -sTCP:LISTEN
COMMAND and PID name the program; the port is in NAME, like *:3000 (LISTEN).
sudo ss -ltnp
The port is after the colon in Local Address:Port; the program is under Process.
netstat -ano | findstr LISTENING
The last column is the process ID. Find its name with tasklist /fi "PID eq 1234".
Start any dev server and run it again: its port appears in the list. To free the port, stop that program.
Open doors and closed doors
A program listening on a port doesn't make it reachable from everywhere. A firewall decides which ports accept connections from outside. A web server usually opens only 443 (and 80, to redirect to 443) to the internet. A database port stays closed to the internet and open only to the app's private network, as in the diagram.
Check yourself