Linux:安装和启用iptables防火墙

今天,在运行docker容器将8080映射为内部80端口时失败。报错内容为“iptables failed”(如下图)。

然后,经过搜索,认为应该启用iptable防火墙,而不是firewall防火墙,然后,就有了iptables防火墙安装和启用的过程。这里记录一下。

对应这个报错,后来通过重启docker解决了。

环境

操作系统:CentOS8 ,已安装Docker(CentOS 8 的docker安装 https://www.cnblogs.com/luyj00436/p/14515187.html

步骤

1. 安装iptable iptables-services。

1 #先检查是否安装了iptables
2 service iptables status
3 #安装iptables
4 yum install -y iptables
5 #升级iptables(安装的最新版本则不需要)
6 yum update iptables 
7 #安装iptables-services
8 yum install iptables-services

 2. 禁用/启用自带的firewall服务。

1 #停止firewalld服务
2 systemctl stop firewalld
3 #禁用firewalld服务
4 systemctl mask firewalld

 3.设置现有规则。

 1 #查看iptables现有规则
 2 iptables -L -n
 3 #先允许所有,不然有可能会杯具
 4 iptables -P INPUT ACCEPT
 5 #清空所有默认规则
 6 iptables -F
 7 #清空所有自定义规则
 8 iptables -X
 9 #所有计数器归0
10 iptables -Z
11 #允许来自于lo接口的数据包(本地访问)
12 iptables -A INPUT -i lo -j ACCEPT
13 #开放22端口
14 iptables -A INPUT -p tcp --dport 22 -j ACCEPT
15 #开放21端口(FTP)
16 iptables -A INPUT -p tcp --dport 21 -j ACCEPT
17 #开放80端口(HTTP)
18 iptables -A INPUT -p tcp --dport 80 -j ACCEPT
19 #开放443端口(HTTPS)
20 iptables -A INPUT -p tcp --dport 443 -j ACCEPT
21 #允许ping
22 iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT
23 #允许接受本机请求之后的返回数据 RELATED,是为FTP设置的
24 iptables -A INPUT -m state --state  RELATED,ESTABLISHED -j ACCEPT
25 #其他入站一律丢弃
26 iptables -P INPUT DROP
27 #所有出站一律绿灯
28 iptables -P OUTPUT ACCEPT
29 #所有转发一律丢弃
30 iptables -P FORWARD DROP
31 #如果要添加内网ip信任(接受其所有TCP请求)
32 iptables -A INPUT -p tcp -s 45.96.174.68 -j ACCEPT
33 #过滤所有非以上规则的请求
34 iptables -P INPUT DROP
35 #要封停一个IP,使用下面这条命令:
36 iptables -I INPUT -s ***.***.***.*** -j DROP
37 #要解封一个IP,使用下面这条命令:
38 iptables -D INPUT -s ***.***.***.*** -j DROP
39 #保存上述规则
40 service iptables save
41 #注册iptables服务
42 #相当于以前的chkconfig iptables on
43 systemctl enable iptables.service
44 #开启服务
45 systemctl start iptables.service
46 #查看状态
47 systemctl status iptables.servic

4. 映射端口。

1 #将默认的3306端口映射长1306对外提供服务
2 iptables -t mangle -I PREROUTING -p tcp --dport 1306 -j MARK --set-mark 883306 
3 iptables -t nat -I PREROUTING -p tcp --dport 1306 -j REDIRECT --to-ports 3306
4 iptables -I INPUT -p tcp --dport 3306 -m mark --mark 883306 -j ACCEPT

参考网址

Centos 7 docker 启动容器 iptables 报 No chain/target/match by that name:https://blog.51cto.com/17099933344/1929664

有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
原文地址:https://www.cnblogs.com/luyj00436/p/14751341.html