How can I close some specific port on Linux?
You can close a port on Linux by either stopping the process that’s listening on that port or by blocking it via a firewall rule. Here are the common approaches:
1. Kill the Process Listening on the Port
- Identify the process bound to a particular port (e.g., port 8080):
You’ll see a line showing a PID (process ID).lsof -i :8080
- Terminate the process:
or if it won’t shut down gracefully:kill <PID>
kill -9 <PID>
- Verify the port is no longer in use:
No output means the port is closed.lsof -i :8080
2. Block the Port via Firewall (iptables Example)
- Drop incoming traffic to a specific port (e.g., port 8080):
sudo iptables -A INPUT -p tcp --dport 8080 -j DROP
- This prevents new connections to the port.
- Persist the firewall rules. The method depends on your distribution:
- Debian/Ubuntu: Use
iptables-save > /etc/iptables.rules
(and restore them on boot). - CentOS/Fedora: Possibly use
firewalld
oriptables-services
.
- Debian/Ubuntu: Use
- Verify:
Look for a rule referencingsudo iptables -L -n
dpt:8080
.
Using ufw (Ubuntu/Debian)
On systems with ufw (Uncomplicated Firewall):
sudo ufw deny 8080/tcp sudo ufw status
You’ll see a rule denying TCP connections on port 8080.
Using firewalld (CentOS/Fedora)
sudo firewall-cmd --add-rich-rule='rule family="ipv4" port port=8080 protocol=tcp drop' --permanent sudo firewall-cmd --reload sudo firewall-cmd --list-all
In each case, the rule either denies or drops traffic on that port, effectively closing it to incoming connections.
Further Learning
If you’d like to combine your Linux/DevOps skills with solid coding and interview preparation, check out these courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews – Develop a deep understanding of fundamental data structures and algorithms, crucial for performance-critical tasks in scripting and application development.
-
Grokking the Coding Interview: Patterns for Coding Questions – Learn the essential coding patterns tested in interviews at top tech companies, helping you solve complex problems more efficiently.
By mastering both system-level knowledge (like managing ports) and strong algorithmic skills, you’ll be well-prepared for a wide range of technical challenges.