Logo

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

  1. Identify the process bound to a particular port (e.g., port 8080):
    lsof -i :8080
    You’ll see a line showing a PID (process ID).
  2. Terminate the process:
    kill <PID>
    or if it won’t shut down gracefully:
    kill -9 <PID>
  3. Verify the port is no longer in use:
    lsof -i :8080
    No output means the port is closed.

2. Block the Port via Firewall (iptables Example)

  1. 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.
  2. 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 or iptables-services.
  3. Verify:
    sudo iptables -L -n
    Look for a rule referencing 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:

  1. 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.

  2. 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.

CONTRIBUTOR
TechGrind