Linux, create local port redirection

The Fritz Box interface opens on the port forwarding.

The following situation: Nextcloud or an Apache web server is running on my home server. Port forwarding is set up. The external domain points to the address of the Fritzbox or the router with a CNAME.

The problem: Port forwarding, Fritzbox reports

On the road everything works. I can access it externally with “subdomain.domain.de”. Only in the home network does the Fritzbox user interface appear. Of course I can use the IP address in the internal network, but it’s stupid for the Nextcloud client on the notebook, for example, because I then have a different server address internally than externally.

One possibility is to reconfigure the Apache server so that it does not run on the same port as the Fritzbox. But I didn’t want to do that, so I looked for a way to redirect a local port. I.e. in the example I release port 8443 via the Fritzbox and forward this to the server. However, the server works on port 443 (https).

Redirect local port

The solution is “socat”, the software allows to redirect a local port to another local port. First we install the software:

sudo apt update
sudo apt install socat

We then redirect port 8443 to 443:

socat tcp-listen:8443,reuseaddr,fork tcp:localhost:443

So far so good, however the redirection is gone again as soon as the command finishes. We can note a & at the end, then a process is started, but only as long as the computer does not restart.

Create systemd service

Now to run the script to start the system, we create a script. It has the following content, important that & at the end.

#!/bin/bash
socat tcp-listen:8443,reuseaddr,fork tcp:localhost:443 &

We can create the script under /root/socat.sh, for example, and then make it executable:

sudo vim /root/socat.sh
sudo chmod +x /root/socat.sh

Now we create a service. There we create a new text file:

sudo vim /etc/system/system/socat.service

The content looks like this, adapt if necessary:

[Unit]
Description=socat script

[Service.]
ExecStart=/root/socat.sh
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

We can then activate the service:

sudo systemctl daemon-reload
sudo systemctl enable socat.service

Done! After the restart, the service is now available. If not, then we can check this with the following command:

sudo systemctl status socat.service

Leave a Reply

Your email address will not be published. Required fields are marked *