DEV Community

loading...

Discussion on: How to properly close a port?

Collapse
capsel profile image
CapSel

Do not use lsof on live Linux (and possibly FreeBSD) servers. In very rare conditions it can cause entire server to hang - hardware reboot needed.

Instead use ss (fast!) and if you really have to then netstat (sloooww, cpu hog).

Collapse
sylwiavargas profile image
Sylwia Vargas Author

Thank you! I don't think I propose it in the post 🤔
What do you think about the steps proposed by mayankjoshi that I integrated into the blog post:

  1. Get a list of all open processes $top
  2. Kill a process kill pid kills the process by process id killall pname kills the process by name -9 for forceful killing in both kill and killall Use sudo if it's a root process.

Would you add anything?

Collapse
capsel profile image
CapSel

ss -tnlp and netstat -tnlp shows pid of processes, their names and their open/listening (aka server) ports. There are tons of tutorials @google about these two commands. top on the other hand does not show open ports. Depending on the OS it can have some shortcuts to kill.

As to root and sudo I would be very careful. You may end up with a surprise ;) You can kill some system service like X server, print spooler, OS upgrade process.

kill (pid) and killall (matching a name) sends signals to processes. Without a name of a signal given default one is used - SIGTERM. This is just "asking" process to exit - similar to alt+f4. The -9 signal is a SIGKILL signal - usually just called kill. It cannot be ignored by processes.

After killing process that had opened TCP port it make take a while before this port is closed. It hangs in OS in special state - only thing you can do is wait or reboot.

Sooner or later you're going to need kill some process to free some port. It's a good idea to glance some docs/manuals (man ss, man netstat) to have some vague memories about what each of these commands can do. Every command is useful. Everyone has their favourite set. Do an experiment - but before you do save your files.