Kodokon kodokon.com

localhost, ports, and "it works on my machine"

Run a server on your own computer and understand why nobody else can see it.

7 min · 3 questions

Open this lesson in Kodokon

When you are building a site, you are not going to publish it to the internet after every single edit. You run a server on your own computer, and you visit it with your browser. That machine, yours, has a reserved name: localhost, literally "the local host". It also has a reserved IP address, 127.0.0.1, which always means "myself", on any machine in the world.

But a computer can run several servers at once. How do you know which one you are talking to? Through ports. If the IP address is the address of the building, the port is the apartment number: a number between 1 and 65535 that identifies the program meant to answer. Some are conventional: port 80 for http, 443 for https. In development, we often use 3000, 5173 or 8000. The port is written after the name, separated by a colon: http://localhost:8000.

BASH
cd my-site
python3 -m http.server 8000

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
A real web server in a single command. On Windows, write py -m http.server 8000.

Leave that terminal window open: as long as the command is running, the server answers. Now open http://localhost:8000 in your browser, and you will see the files in the my-site folder. To stop the server, go back to the terminal and press Ctrl + C.

Why go to all that trouble, when double-clicking index.html opens the page too? Because a double-click opens the file at the address file:///C:/Users/..., not http://. And several web features flat out refuse to work outside the http protocol: requests to a server, JavaScript modules, certain fonts. You will get baffling errors that vanish as if by magic the moment you go through localhost.

BASH
lsof -i :8000

COMMAND   PID   USER   FD   TYPE  NODE NAME
python3  4821  sarah    3u  IPv4   TCP *:8000 (LISTEN)
Who is holding port 8000? On Windows: netstat -ano | findstr :8000

Knowledge check

Make sure you remember the key points of this lesson.

  1. Put these commands back in order to create a folder, move into it, then start a local server there.
    mkdir site
    cd site
    python3 -m http.server 8000
  2. Why can't a colleague see your site when they open http://localhost:3000?
    • Because the port number is wrong on their machine
    • Because localhost refers to their own machine, not yours
    • Because they should be using https
  3. What is the port number in http://localhost:8000 for?
    • Indicating which program on the machine should answer
    • Encrypting the communication
    • Numbering the pages of the site