Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Route traffic between alias ip and elastic ip

Hello,

I have setup where I am looking to route traffic between alias ip and elastic ip(public ip) both attached to Nic2 of a linux vm. 

As httpd is only running on alias ip and not nic2 ip. So I am not able to reach httpd service which is running on alias ip.  Also this setup has vpn connectivity so I can't add many routes.

Currently I am using a NAT to reach nic2 ip. But need to reach alias ip. 

ip forwarding is enabled, tried policy based routing in linux itself didn't work. 

I can't forward all the traffic from nic2 to alias ip. as alias ip is also attached to nic2 and nic2 runs other services .

I did look at passthrough proxy as suggested by gcp support but it won't fit our use case. as its not ip to ip but ip to group of vms.

1 1 228
1 REPLY 1

Hi @vanilnew ,

By the looks of it, you're trying to route traffic from the external (Elastic IP) to the internal (alias IP) of a Linux VM, where the HTTP'd service is running on the alias IP, however you can't use policy-based routing or forward all traffic from the NIC2 to the alias IP.

You can try using iptables to perform destination NAT. 

1. Using the command below, make sure IP forwarding is enabled on your system.

cat /proc/sys/net/ipv4/ip_forward
 
note: If the output is 0, IP forwarding is disabled. Change it to 1.
 
echo 1 > /proc/sys/net/ipv4/ip_forward
 
2. Next, set up a DNAT rule using iptables. 
 
iptables -t nat -A PREROUTING -p tcp -d <destination_ip> --dport <destination_port> -j DNAT --to-destination <target_ip>

Replace <destination_ip> with the public Elastic IP address, <destination_port> with the port number you want to forward (in this case, 80 for HTTP), and <target_ip> with the alias IP address.

For example, if your Elastic IP is 1.2.3.4, your alias IP is 10.0.0.2, and your HTTP server is listening on port 80, you would run:

iptables -t nat -A PREROUTING -p tcp -d 1.2.3.4 --dport 80 -j DNAT --to-destination 10.0.0.2

This should rewrite the destination IP of incoming HTTP traffic from the Elastic IP to the alias IP.

3. To save and restore your iptables rules, you can use a tool like iptables-persistent.

Let me know if this helps.