共计 2494 个字符,预计需要花费 7 分钟才能阅读完成。
#!/bin/bash
# 后端服务器地址,以空格分开,可改为网段如172.18.241.181/24
server_ips="10.88.40.61 10.88.40.62"
# 对所有主机都开放的端口
tcp_ports="22 80 443 30080 30001 30002 30000-32767"
udp_ports=""
# docker 网段
docker_range="172.17.0.0/8"
# 根据ip获取网卡名称
ipaddress=$(ip r get 1 | awk 'NR==1 {print $NF}')
net_name=$(ip r get 1|awk "/$ipaddress/ {print \$5}")
# 获取docker0ip
docker0_ip=$(ip addr show docker0|grep "inet\b"|awk '{print $2}')
# 首先开启firewalld
systemctl restart firewalld
# 移除掉DOCKER-USER并新建一个(这步非常重要,即便DOCKER-USER存在,也要执行删除。不然不生效)
firewall-cmd --permanent --direct --remove-chain ipv4 filter DOCKER-USER
firewall-cmd --permanent --direct --remove-rules ipv4 filter DOCKER-USER
firewall-cmd --permanent --direct --add-chain ipv4 filter DOCKER-USER
# 添加规则,注意REJECT规则一定要在最后执行,同时注意不建议多个IP地址写在同一条规则,格式上没有问题,但是通过iptables -L确认时,顺序会打乱。导致先被REJECT
# 允许后端服务器之间的所有流量
for server_ip in $server_ips
do
# firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="$server_ip/32" accept"
# firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="$server_ip" port protocol="tcp" port="0-65535" accept"
firewall-cmd --permanent --zone=trusted --add-source=$server_ip
firewall-cmd --permanent --direct --add-rule ipv4 filter DOCKER-USER 0 -s $server_ip -j ACCEPT -m comment --comment "allw server from docker"
done
# 注意这个docker0为网卡名称
firewall-cmd --permanent --direct --add-rule ipv4 filter DOCKER-USER 0 -i docker0 -j ACCEPT -m comment --comment "allows incoming from docker"
# firewall-cmd --permanent --direct --add-rule ipv4 filter FORWARD_direct 0 -o $net_name -j ACCEPT
# firewall-cmd --permanent --direct --add-rule ipv4 filter FORWARD_direct 0 -i $net_name -j ACCEPT
firewall-cmd --permanent --direct --add-rule ipv4 filter DOCKER-USER 0 -i docker0 -o $net_name -j ACCEPT -m comment --comment "allows docker to $net_name"
firewall-cmd --permanent --direct --add-rule ipv4 filter DOCKER-USER 0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -m comment --comment "allows docker containers to connect to the outside world"
# 注意,这个$docker0_ip为docker0的地址
firewall-cmd --permanent --direct --add-rule ipv4 filter DOCKER-USER 0 -j RETURN -s $docker0_ip -m comment --comment "allow internal docker communication"
# 指定public开通端口页面访问的端口
for port in $tcp_ports
do
firewall-cmd --zone=public --permanent --add-port=$port/tcp
done
for port in $udp_ports
do
firewall-cmd --zone=public --permanent --add-port=$port/udp
done
# 添加 docker 使用的容器段
firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address=$docker_range accept"
firewall-cmd --permanent --zone=trusted --change-interface=docker0
firewall-cmd --permanent --zone=trusted --change-interface=cni0
# 永久保存
firewall-cmd --add-masquerade --permanent
# 重新加载
firewall-cmd --reload
正文完