Introduction
CentOS7 provides the Filewalld default firewall. However, a large number of users are still accustomed to using iptables in the CentOS7 system. This article uses CentOS7.4 as an example to describe how to install and use iptables in the CentOS7 system.
Background
Disable Filewalld from starting at startup.
To prevent conflicts with iptables, you must first disable the boot of Filewalld.
- Connect to a CentOS 7.4 instance. For more information about how to connect to a CentOS 7.4 instance, seeconnect to a Linux instance using username and password.
- Run the following command to view the service status:
systemctl status firewalld
A similar output is displayed: the active field indicates that the service is running. The inactive field indicates that the service is disabled. - When the service is in the active state, run the following command to disable the Firewalld service:
systemctl stop firewalld
- Run the following command to disable the startup of Filewalld.
systemctl disable firewalld
Install iptables
Run the following command to install iptables:
yum install -y iptables-services
Start iptables and enable it at startup.
-
Run the following command to start iptables:
systemctl start iptables
-
Run the following command to check whether iptables is started:
systemctl status iptables
If a similar output is displayed, iptables is started. - Run the following command to set iptables to start at boot.
systemctl enable iptables.service
- Run the following command to restart the instance to verify the configurations:
systemctl reboot
View and modify the default iptables rules
Run the iptables-L
command to view the default rules of iptables. The result shows that the chain allows access from any host under the default rules. To modify the default rules, follow these steps.
-
If rules have been set before, run the following command to back up the original iptables file and avoid losing the configured rules.
cp -a /etc/sysconfig/iptables /etc/sysconfig/iptables.bak
- Run the following command to delete all rules:
iptables -F
-
Add rules based on service requirements to allow or disable ports. Example: run the following commands in sequence to allow ports 80 and 22.
iptables -I INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
For example, run the following commands in sequence to add a rule so that the INPUT chain rejects all requests, that is, the ECS instance rejects all requests. Do not directly operate online services. Service interruption may occur.
iptables -I INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
iptables -P INPUT DROP
- Run the following command to confirm that the new rules take effect.
iptables -L
-
Run the following command to save the added rule:
iptables-save > /etc/sysconfig/iptables
Application scope
- ECS