How to configure iptables on CentOS

CentOS is an enterprise-class Linux operating system that's supported by a community of users and developers. It's intended to be completely compatible with Red Hat Enterprise Linux, which is CentOS's upstream source. CentOS has a powerful firewall built into it that uses a set of rules to determine the traffic that will be allowed to enter and exit a network. System administrators can configure a CentOS firewall with the iptables userspace module. Iptables allows administrators to enter rules for the firewall into existing tables from the command line.

DIFFICULTY Basic - 1 | Medium - 2 | Advanced - 3
TIME REQUIRED 15 min
RELATED PRODUCTS CentOS-based VPS or dedicated servers

Here is a quick tutorial on how to setup a firewall on CentOS. This tutorial creates a simple rule set that blocks some incoming connections, while allowing all outgoing connections.

Start the firewall

Sign on to your server as root and open a command window. Ensure that iptables is running with the following command:

# iptables -L

The above command should produce output similar to the following:

Start iptables with the following command if it isn't already running:

# /etc/init.d/iptables start

Write the rule set

Flush the existing rules with this command:

# iptables -F

This command drops an incoming packet if it doesn't match any rules:

# iptables -P INPUT DROP

The computer in this example isn't being used as a router, so the following command drops a forwarded packet if it doesn't match any rules:

# iptables -P FORWARD DROP

Users on this computer are trusted, so outgoing packets will be allowed unless a rule specifically prohibits it:

# iptables -P OUTPUT ACCEPT

Many applications must communicate with the localhost interface, so this rule will allow incoming packets that are destined for localhost:

# iptables -A INPUT -i lo -j ACCEPT

This rule loads the state module which examines the incoming packets, and accepts those that are part of an established connection or related to such a connection.

# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Save the rules with the following command so that they'll be automatically reloaded when you reboot your computer:

# /etc/init.d/iptables save

Display the new settings

Use the following command to verify that the rules you've just added have been loaded correctly:

# iptables -L -v

The above command will produce output similar to the following screenshot:


Var den här artikeln till hjälp?
Tack för din feedback. Ring vårt supportnummer eller starta chattalternativet ovan om du vill prata med en medarbetare på kundtjänst.
Vi är glada att vi kunde hjälpa till! Finns det något mer vi kan göra för dig?
Det var tråkigt att höra. Berätta vad som var krångligt eller varför lösningen inte hjälpte dig med problemet.