CentOS 7 – Fix Firewalld Port Forwarding Not Working

centos7firewalld

In my server I wanted to redirect all request:
come from 81 to 8080 port

Because Jenkins service is not allowed listened at 80 port, I follow Jenkins doc
Jenkins – Reverse proxy using firewalld.

But not working, below is my step and some system details:

  1. CentOS version = 7.9.2009
[root@xxx ~]# cat /etc/centos-release
CentOS Linux release 7.9.2009 (Core)
  1. I have enabled the port and added port forwarding rule in firewalld:
    (Already add permanent and reload firewalld)
[root@xxx ~]# firewall-cmd --list-all --zone=public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens160 lo
  sources:
  services: dhcpv6-client http ssh
  ports: 80/tcp 443/tcp 81/tcp
  protocols:
  masquerade: yes
  forward-ports: port=81:proto=tcp:toport=8080:toaddr=
  source-ports:
  icmp-blocks:
  rich rules:
  1. check netstat:
[root@xxx ~]# netstat -tulpn | grep LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1090/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1724/master
tcp6       0      0 :::8080                 :::*                    LISTEN      1107/java
tcp6       0      0 :::22                   :::*                    LISTEN      1090/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1724/master

Only 8080/22/25 be listened on.

  1. I try to use nc tool to check port forwarding:
[root@xxx ~]# nc -v 127.0.0.1 8080
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 127.0.0.1:8080.
^C
[root@xxx ~]# nc -v 127.0.0.1 81
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connection refused.

8080 is ok, but 81 forwarding not working.

  1. Some reference said need to set net.ipv4.ip_forward=1.
    I also set already before:
[root@xxx ~]# sysctl -a |grep "ip_forward"
net.ipv4.ip_forward = 1
net.ipv4.ip_forward_use_pmtu = 0
sysctl: reading key "net.ipv6.conf.all.stable_secret"
sysctl: reading key "net.ipv6.conf.default.stable_secret"
sysctl: reading key "net.ipv6.conf.ens160.stable_secret"
sysctl: reading key "net.ipv6.conf.lo.stable_secret"
  1. Double check my iptables, and I didn't setup iptables:
[root@xxx ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
[root@xxx ~]# systemctl status iptables
Unit iptables.service could not be found.

Any ideas for how to work "port-forwarding" using firewalld?
Thanks.

Best Answer

Finally, I found a solution. And one more thing, netstat can not check port-fowarding.

Need to add direct rule for lo:

[root@xxx ~]$ firewall-cmd --direct --get-all-rules
ipv4 nat OUTPUT 0 -p tcp -o lo --dport 80 -j REDIRECT --to-ports 8080