当前位置:首页 > 问答 > 正文

端口转发|网络配置_CentOS端口映射详解与设置方法

核心关键词与概念

  1. 端口转发(Port Forwarding)

    端口转发|网络配置_CentOS端口映射详解与设置方法

    • 定义:将外部网络请求的特定端口流量重定向到内部网络的另一端口或主机。
    • 类型:本地端口转发、远程端口转发、动态端口转发。
  2. CentOS网络配置工具

    端口转发|网络配置_CentOS端口映射详解与设置方法

    • firewalld(默认防火墙工具)
    • iptables(传统防火墙,CentOS 7/8仍支持)
    • nftables(CentOS 8+推荐替代iptables)

CentOS端口映射设置方法

方法1:使用firewalld

  1. 启用防火墙并检查状态:
    systemctl start firewalld  
    systemctl enable firewalld  
    firewall-cmd --state  
  2. 添加端口转发规则(例:将外部80端口转发到内网192.168.1.100的8080端口):
    firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toaddr=192.168.1.100:toport=8080  
    firewall-cmd --reload  

方法2:使用iptables

  1. 开启内核IP转发:
    echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf  
    sysctl -p  
  2. 添加NAT规则(例:转发外网eth0的80端口到内网192.168.1.100:8080):
    iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to 192.168.1.100:8080  
    iptables -t nat -A POSTROUTING -j MASQUERADE  
    service iptables save  

方法3:使用nftables(CentOS 8+)

  1. 创建端口转发规则:
    nft add table nat  
    nft add chain nat prerouting { type nat hook prerouting priority 0 \; }  
    nft add rule nat prerouting tcp dport 80 dnat to 192.168.1.100:8080  

常见问题与验证

  • 验证端口转发是否生效
    ss -tulnp | grep <端口号>  
    或  
    firewall-cmd --list-all  
  • 关键配置项
    • 确保SELinux未阻止转发(可临时设置为permissive模式测试)。
    • 检查目标主机的防火墙是否放行转发的端口。

注意事项

  1. 生产环境中建议结合--permanent参数保存规则。
  2. 若使用云服务器,需额外配置安全组/网络ACL规则。
  3. CentOS版本差异:
    • CentOS 7默认使用firewalld+iptables
    • CentOS 8+逐步转向nftables后端。

发表评论