How to forward a TCP port using systemd + socat
A common problem I need to solve with my web servers are simple TCP port forwarding. This allows you to redirect an application traffic, from a HTTP server for example, to another port or even server. There are many ways of achieving this goal and this post will guide you to solve this problem using systemd and socat.
Requirements
You need to have a Linux distribution using systemd and you must have socat installed.
# If you are using Fedora/CentOS/RHEL
dnf install -y socat
# If you are using Debian/Ubuntu
apt update
apt install -y socatinstall socat
Create the systemd service
I'm assuming the following scenario for this example:
Server 192.168.1.10receives the request fromport 80and -> send traffic toServer 192.168.1.20andport 9000.
# Service in the 192.168.1.10 server
[Unit]
Description=Forward TCP port 80 via socat
Documentation=man:socat(1)
[Service]
ExecStart=/usr/bin/socat TCP-LISTEN:80,forever,interval=10,fork,reuseaddr TCP:192.168.1.20:9000
Restart=always
# If you are listening a port between 1-1023,
# then you need to be root. Otherwise, you
# can the user to nobody.
User=root
RestartSec=10
[Install]
WantedBy=multi-user.target/etc/systemd/system/socat-http-example.service
Now, enable the service and that's it!
systemctl daemon-reload
systemctl enable --now socat-http-example
systemctl status socat-http-examplereload systemd configs and enable the service