Search code examples
amazon-web-servicesamazon-ec2elastic-ip

Assign Multiple EC2 instances to one Elastic IP


I have 2 EC2 instances and they send requests to an external server. That server requires a static IP, so I used Elastic IP to connect one of the EC2s to it.

The problem is that I'm only allowed to have one static IP associated with my account on that server. Is there a way to put the 2 EC2s behind the same EIP using network interface or ELB? I tried to read about it, but AWS documentation is a bit overwhelming.


Solution

  • The simplest method is to:

    • Create a NAT Gateway in a public subnet
    • Put your EC2 instances in a private subnet
    • Configure the routing for the private subnet to send internet-bound traffic to the NAT Gateway

    This way, all traffic will appear to be coming from the NAT Gateway, which can have a single Elastic IP address.

    An alternate method would be to use one of the instances (Instance-A) as a NAT Instance, which uses a masquerade setting in iptables to forward traffic. Then, configure the second instance (Instance-B) to send internet-bound traffic to Instance-A. Instance-A will forward the traffic to the external server and pass the response back to Instance-B.

    This is the normal script to configure an EC2 instance as a NAT Instance:

    #!/bin/sh
    echo 1 > /proc/sys/net/ipv4/ip_forward
    echo 0 > /proc/sys/net/ipv4/conf/eth0/send_redirects
    /sbin/iptables -t nat -A POSTROUTING -o eth0 -s 0.0.0.0/0 -j MASQUERADE
    /sbin/iptables-save > /etc/sysconfig/iptables
    mkdir -p /etc/sysctl.d/
    cat <<EOF > /etc/sysctl.d/nat.conf
    net.ipv4.ip_forward = 1
    net.ipv4.conf.eth0.send_redirects = 0
    EOF