Simple IPTables OpenVZ Setup

So after looking and failing to find a good article on how to describe the simple process to set up IPTables on an OpenVZ server, I figured I would write one here. The process is incredibly simple and can be broken down into 3 steps:

  1. Empty out the contents of /etc/sysconfig/iptables
    cat "" > /etc/sysconfig/iptables
  2. Use the following line in /etc/sysconfig/iptables-config:
    IPTABLES_MODULES="ipt_REJECT ipt_tos ipt_TOS ipt_LOG ip_conntrack ipt_limit ipt_multiport iptable_filter iptable_mangle ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_length ipt_state iptable_nat ip_nat_ftp"
  3. Use the following line in /etc/vz/vz.conf:
    IPTABLES="ipt_REJECT ipt_tos ipt_limit ipt_multiport iptable_filter iptable_mangle ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_length ipt_state"

After ensuring these three things, just stop both vz and iptables, start iptables, then start vz. You should then be able to use iptables within a virtualized container.

Scripting IP additions in OpenVZ

So I just had an interesting issue where I was trying to add 60 IPs to 30 OpenVZ instances, 2 IPs per node. I came up with the following script to do so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
for i in `vzlist -a | grep -v CTID | awk '{print $1}'`
do
     let k=0
     for j in `cat /root/ips`
     do
          if [ $k -lt 2 ]
          then
               vzctl set $i --ipadd $j --save
               let k=k+1
          else
               sed -i '1,2d' /root/ips
               break
          fi
     done
done

The main things to note here are the following:

  • When assigning a variable a value in a for loop, you need to use “let” before declaring it
  • SED can be used to remove lines just as it can be used to add and replace items in lines
  • Break is not something to be afraid of!

In any case, this script might be handy for others trying to perform similar tasks so I’ll just leave it here. Feel free to modify and use this code as you please 🙂 Let me know if you have any optimizations you can think of in the comments below.