How to use an Amazon EC2 instance as a VPN server

One day I was doing some testing and I wanted to be sure it wasn’t my DNS/Routes that were causing the response time issues. A co-worker suggested using an EC2 instance as a VPN server. I thought that would be perfect!

I’m going to assume that you have the knowledge of starting up an Ubuntu EC2 instance.

First up is installing OpenVPN and enabling ip forwarding:

sudo apt-get install -y openvpn
sudo modprobe iptable_nat
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
sudo iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE

Next up is generating a shared key for authentication/encryption.

cd /etc/openvpn
sudo openvpn --genkey --secret ovpn.key

Here’s a basic conf file (/etc/openvpn/openvpn.conf). Read the OpenVPN man page for more options.

port 1194
proto tcp-server
dev tun1
status server-tcp.log
verb 3
secret  ovpn.key

Now to start it and follow the status:

sudo service openvpn start
tail -f /etc/openvpn/server-tcp.log

Make sure tcp port 1194 is open in your instance’s security group!

scp/email/ftp/rsync/nc the ovpn.key file to your client machine.
Start OpenVPN client on your client machine:

export EC2_IP=
sudo openvpn                    \
  --proto tcp-client            \
  --remote $EC2_IP          \
  --port 1194                     \
  --dev tun1                    \
  --secret ovpn.key             \
  --redirect-gateway def1       \
  --ifconfig  \

Now if you visit it should be your EC2 Instance’s IP.

  • Pingback: Tweets that mention How to use an Amazon EC2 instance as a VPN server « Dctr Watson --

  • tv shows

    Why god allows this sort of thing to continue is a mystery.

    Sent via Blackberry

  • recluze

    Thanks a lot for the tutorial. I did the rest but forgot the internal iptables routing. It helped a lot. :)

  • US VPN

    I feel the same way as it helped me too.

  • alexplugaru

    sudo iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE
    should probably be: 

    sudo iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE

    • Aaron

      Thanks!! Will try soon.

  • Marshal Drake

    Thanks for sharing this good info. The only problem is, is there an additional cost for using their EC2 as VPN Server.

    chicago colocation

  • Pingback: amazon ec2 pricing()

  • Aaron

    Let’s say that I have a local server that is blocked by an ISP from public hosting (caught behind NAT). I connect to EC2 via OpenVPN. I now how on EC2 an private IP of I want traffic to my public IP (elastic IP. ex. 12.34.567.89) to route to the private IP to enable public access to my local server. How does one configure such routing?

    • John Watson

      I haven’t tried it, but I suppose you could do some neat tricks with iptables on both ends to get it to work.