HOWTO: KVM — build ubuntu guest VM, bridge network and iptables port forwarding

Once you install and setup KVM, configure kvm itself and system network bridge interface correctly on your Ubuntu server, you can now starting to build a guest OS / disk image, run it, and use iptables to forward connections to those new VPSes.

Build guest:

HTTP_PROXY="Proxy_IP:Port" sudo ubuntu-vm-builder kvm hardy \
--dest 'DEST_DIR'\
--hostname 'GUEST_HOSTNAME'\
--ip 'GUEST_IP_YOU_WANT'\
--arch 'i386'\
--mem '256'\
--rootsize '4096'\
--swapsize '1024'\
--kernel-flavour 'virtual'\
--domain 'bluet.org'\
--mirror 'http://ftp.twaren.net/ubuntu'\
--components 'main,universe,multiverse,restricted'\
--addpkg ssh --addpkg vim --addpkg unattended-upgrades --addpkg acpid\
--name 'Default_User_Name' --user 'Default_User_Account' --pass 'Default_User_Password'\
--mask '255.255.255.0'\
--net '192.168.122.0'\
--bcast '192.168.122.255'\
--gw '192.168.122.1'\
--dns '192.168.122.1'\
--tmp '/dev/shm/'\
--libvirt qemu:///system ;

Modify that to fit your needs.

Forward “connections to specific port on HostOS” to a specific port on GuestOS (VPS):

Run these commands in HostOS:

$ sudo iptables -t nat -I PREROUTING -p tcp -d HostOS_IP --dport HostOS_Port -j DNAT --to GuestOS_IP:GuestOS_Port
$ sudo iptables -A FORWARD -p tcp -d GuestOS --dport GuestOS_Port -j ACCEPT

For example, if you want to ssh to your VPS, you can pick a spare (not-using by other application) port, and forward “connections to the specified port on HostOS” to the GuestOS’s port 22.
Let’s say, when HostOS is using IP 192.168.1.2, GuestOS is using IP 192.168.122.2, the choosen port on HostOS is 10022, you can do the following commands.

$ sudo iptables -t nat -I PREROUTING -p tcp -d 192.168.1.2 --dport 10022 -j DNAT --to 192.168.122.2:22
$ sudo iptables -A FORWARD -p tcp -d 192.168.122.2 --dport 22 -j ACCEPT

Finally, you got a configured VPS, you can start running it and ssh into it.

Start the VPS:

If your GuestOS’ hostname is “vps01”, you can do this to start running it:

$ virsh start vps01

And then ssh into it:

$ ssh -v 192.168.1.2 -p 10022

Refs: KVM document page on ubuntu.com


Originally published at blog.geeky.name on September 24, 2009.

GeekyLog

BlueT’s LoGeeks, Logics of Geeky Thoughts.

BlueT / Matthew Lien 練喆明

Written by

Just another Perl / OpenSource / Security Hacker. CTO / Co-founder @Imonology, Leader @Ubuntu_TW, Founder @OSSPlanet. Promote Ubuntu Linux, Networking, Privacy.

GeekyLog

GeekyLog

BlueT’s LoGeeks, Logics of Geeky Thoughts.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade