Saturday, December 22, 2012

Use Your Local Database IP References (or other Resources) Without Altering Code

So you want your code to point to your local IP database references but want to avoid changing code or maintaining configuration values separate for production and development? Here's how.

The principle is to use iptables (works only on Linux kernels and alike), and route the outgoing packets even before they try to resolve and reach the network resource, in this case a database server, they need to connect to. Here's the example.

 iptables -t nat -A OUTPUT -p tcp -d <production database IP> -j DNAT --to-destination

The sample says that we are going to use the routing table type called 'nat' as specified by "-t nat". Then, apply it to output rules that govern outgoing packets as specified by "-A OUTPUT". Next is to say that the transport protocol it is applicable with is TCP via "-p tcp -d <production database IP>". Lastly, when the packet rule is detected, jump back to your localhost as stated by "-j DNAT --to-destination".

Now, you are accessing your database resource in your localhost but your code says you are connecting via your production database IP. This cool trick applies to several other use-cases such as.

1. Distributing reads and writes to databases of which you can have your System Administrators have more control as to where they should re-route requests without developer intervention. Like when a server has crashed and you have a handy failover redundancy.

2. You want to maintain legacy IP references to point to a new system, without bothering to change the legacy code that has all the IPs scattered all over. Very applicable for hybrid environments or transition-state environments.

3. And of course the example above, of which you want to not change code but wanted to point everything to your local copy for development purposes.

4. This same principle applies to none database network resources that your application uses, like a search engine api, image processor, cgi etc.

Note: This was tested to work on Ubuntu, CentOS/RHEL and Fedora. It would mostly likely work on any flavor of Linux or Unix that has the iptables installed with support to the options explained above.

  • Related Links Widget for Blogspot

No comments: