7

I'm running Amazon Linux 2, on EC2 instances in AWS. I want to be able to add my own iptables rules, and have them survive reboots.

What is the correct way (or a correct way) to do this?

Richard Downer
  • 411
  • 1
  • 3
  • 9

1 Answers1

16

A simple way to do this (which works at the time of writing, with an AMI image timestamped at 2020-05-20) is to enable the iptables service. This allows rules to be saved to the system configuration, and be applied every time the instance boots.

First, install the service and activate it:

yum install iptables-services -y
systemctl enable iptables
systemctl start iptables

Second, add whatever iptables rules you like.

For example:

# Enable NAT forwarding
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Then, whenever you change the iptables rules:

service iptables save

The currently-applied set of rules are saved to /etc/sysconfig/iptables, and are restored on every boot.

Richard Downer
  • 411
  • 1
  • 3
  • 9
  • 1
    If one forgets to install `iptables-services`, the last command gives a rather confusing `The service command supports only basic LSB actions... please try to use systemctl." – Aleksandr Dubinsky Nov 07 '21 at 06:39