How to configure haproxy load balancing on amazon ec2

Confused how to configure load balancer on Amazon. Here we given you detail instructions about How to configure haproxy load balancing on amazon EC2

Many people take amazon EC2 cloud hosting. Amazon does gives the load balancer for application load balancing. But Amazon load balancer is not that much good. Amazon load balancer is not working on hardware or software base. That balancer just sending request to server one by one. Many people confused how to configure load balancer on Amazon EC2.

Here I am going to give you detail instructions about setting up the HaProxy load balancer on Amazon EC2.

How to configure haproxy load balancing on amazon ec2

What is Haproxy?

AProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications. It is particularly suited for web sites crawling under very high loads while needing persistence or Layer7 processing. Supporting tens of thousands of connections is clearly realistic with todays hardware. Its mode of operation makes its integration into existing architectures very easy and riskless.

How to configure haproxy load balancing on amazon ec2
How to configure haproxy load balancing on amazon ec2

For Haproxy load balancing I recommend to create the micro instance first. Then login to micro instance and install haproxy on that machine. I taken the Centos 5.0 virgin os. Use following command for install the haproxy.

#yum install haproxy

Then Open the haproxy config file.

# vi /etc/haproxy.cfg

For detail configuration you should read the Haproxy config documentation.

http://haproxy.1wt.eu/download/1.3/doc/configuration.txt

Haproxy’s default load balancing style is roundrobin. Which is trusted and good. With this load balancing I am serving around two million pages daily. Means I am handling 6 to 7 million requests per day. I am not having any issues.

I used the three backend server for delivery of my application and one server for serving the static data which is having images and js and css and application files.

Here is my configuration file


global
 maxconn     4096 # Total Max Connections. This is dependent on ulimit
 daemon
 nbproc      4 # Number of processing cores. Dual Dual-core Opteron is 4 cores for example.

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
 mode        http
 log         global
 option      dontlognull
 option      httpclose
 option      httplog
 option      forwardfor
 option      redispatch
 timeout connect 10000 # default 10 second time out if a backend is not found
 timeout client 300000
 timeout server 300000
 maxconn     60000
 retries     3

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
#frontend  main *:80
frontend http-in
 bind :80
 acl url_static       path_beg       -i /static /images /javascript /stylesheets
 acl url_static       path_end       -i .jpg .gif .png .css .js
 acl url_stats        path_beg    /haproxy-stats
 use_backend        be_stats    if url_stats

 use_backend static          if url_static
 default_backend             app

#-------------------------------------------------
#back-end statistics section
#----------------------------------------------------------------
backend be_stats
 stats uri /haproxy-stats
#    stats show-node

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend static
 balance     roundrobin
 server      static 10.211.164.138:80 check
 #server      static 10.211.185.111:80 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
 balance     roundrobin
 server  app1 10.214.284.241:80 check
 server  app2 10.208.168.131:80 check
 server  app3 10.212.158.126:80 check

You can use the above code in haproxy.cfg file. You just need to change the IP address which are listed under backend static and backend app section. You just put your static server(amazon EC2 instance’s internal IP address).

You should use internal IP address of server because that will reduce the bandwidth uses of Amazon EC2 server. Do not use the public IP address for load balance because that will cost you.

Put application database and application files on all the server. Point your domain to your load balancer machine’s Public IP address.

Let say your application is running on following domain.

www.YOURDOMAIN.COM – point to Load balancer macine.

Open your all application and static server’s apache configuration file. put following entry in that file.


<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.YOURDOMAIN.COM

# Other directives here

</VirtualHost>

after this just restart the apache server of all servers.

If you are having any issues or questions about setting up the haproxy on amazon EC2 server Please write to me.

File upload with meta box in wordpress with custom post type

Code for File upload with meta box in wordpress using custom post type using meta boxes in wordpress. From wordpress 3.0 version wordpress introduced the custom_post_type function. Many people want to attach the file field with add_meta_box function. In this tutorial I will tell you how to upload file with custom meta box and post type. I tested above code with new wordpress versions 3.9. Still code is working fine.

Code for File upload with meta box in wordpress using custom post type using meta boxes in wordpress.

In this tutorial I will show you how to create the custom post type and add custom meta boxes to that post type and upload file with custom meta box.

After digging into wordpress files and functions I created following code. Just open your functions.php file and put following code in that file for creating custom post type.


<?php
 add_action('init', 'create_product');
 function create_product() {
 $product_args = array(
 'label' => __('Product'),
 'singular_label' => __('Product'),
 'public' => true,
 'show_ui' => true,
 'capability_type' => 'post',
 'hierarchical' => false,
 'rewrite' => true,
 'supports' => array('title', 'editor', 'thumbnail')
 );
 register_post_type('product',$product_args);
 }
?>

For uploading the file through custom meta box use the following code. Following code will add the file field to custom meta box and you are able to upload file or image to wordpress and upload file attachment to you custom post. Following code is very helpful to many wordpress theme and plugin developer. If you are having any issues or trouble using code then get back to me.

File upload with add_meta_box or custom_post_type in wordpress File upload with meta box in wordpress
File upload with add_meta_box or custom_post_type in wordpress File upload with meta box in wordpress

<?php

 add_action("admin_init", "add_product");
 add_action('save_post', 'update_purchase_url');
 function add_product(){
 add_meta_box("product_details", "product Options", "product_options", "product", "normal", "low");
 }
 function product_options(){
 global $post;
 $custom = get_post_custom($post->ID);
 $purchase_url = $custom["purchase_url"][0];
 $product_price = $custom["product_price"][0];
 $product_image = $custom["product_image"][0];
 $video_code = $custom["video_code"][0];

?>
 <div id="product-options">
 <label>Purchase URL:</label>php echo $purchase_url; ?>" />

 <label>Product Price:</label>php echo $product_price; ?>" />

 <label>Product Image:</label>php echo $product_image; ?>" />
 <img src="<?php echo $product_image; ?>">

 </div><!--end product-options-->
<?php
 }
 function update_purchase_url(){
 global $post;
 update_post_meta($post->ID, "purchase_url", $_POST["purchase_url"]);
 update_post_meta($post->ID, "product_price", $_POST["product_price"]);
 update_post_meta($post->ID, "product_image", $_POST["product_image"]);

 if(!empty($_FILES['product_image']['name'])){ //New upload
 require_once( ABSPATH . 'wp-admin/includes/file.php' );
 $override['action'] = 'editpost';

 $uploaded_file = wp_handle_upload($_FILES['product_image'], $override);

 $post_id = $post->ID;
 $attachment = array(
 'post_title' => $_FILES['product_image']['name'],
 'post_content' => '',
 'post_type' => 'attachment',
 'post_parent' => $post_id,
 'post_mime_type' => $_FILES['product_image']['type'],
 'guid' => $uploaded_file['url']
 );
 // Save the data
 $id = wp_insert_attachment( $attachment,$_FILES['product_image'][ 'file' ], $post_id );
 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $_FILES['product_image']['file'] ) );

update_post_meta($post->ID, "product_image", $uploaded_file['url']);
 }
 }
?>

For Uploading the file your post form need to add the enctype=”multipart/form-data” type to your form. Just use the following code in your functions.php file.

[viral-lock message=”Solution code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]


<?php
function fileupload_metabox_header(){
?>
<script type="text/javascript">
 jQuery(document).ready(function(){
 jQuery('form#post').attr('enctype','multipart/form-data');
 jQuery('form#post').attr('encoding','multipart/form-data');
 });
</script>
<?php }
add_action('admin_head', 'fileupload_metabox_header');

?>

[/viral-lock]

For checking all information in edit or preview section use following code.


<?php

add_action("manage_posts_custom_column",  "product_custom_columns");
add_filter("manage_edit-product_columns", "product_edit_columns");

function product_edit_columns($columns){
 $columns = array(
 "cb" => "<input type=\"checkbox\" />",
 "title" => "Product Title",
 "purchase_url" => "Purchase URL",
 "product_price" => "Product Price",
 "product_image" => "Product Image",
 );
 return $columns;
}
function product_custom_columns($column){
 global $post;
 switch ($column) {
 case "purchase_url":
 $custom = get_post_custom();
 echo $custom["purchase_url"][0];
 break;
 case "product_price":
 $custom = get_post_custom();
 echo $custom["product_price"][0];
 break;
 case "product_image":
 $custom = get_post_custom();
 $img_url =$custom["product_image"][0];
 echo "<image src=".$img_url." height=100 width=100 />";
 break;
 }
}

?>

File upload with meta box in wordpress
File upload with meta box in wordpress

Above code is useful for any type of customization. If you are having any issue with using this code then please get back to me.

How to use custom post type in wordpress

From wordpress 3.0 version release wordpress gives the facility to add a custom post type functionality. With custom post type wordpress is became more powerful and expendable and more advanced We given info about, How to use custom post type in wordpress.

How to use custom post type in wordpress

WordPress recognized the need to people and industry and they introduced the custom post type. In this tutorial I will tell you how to use the custom post type very effectively.

Adding Custom post type is very easy. Using theme or plugin file you can add the custom post types in wordpress admin area.

Here I am going to give you example using wordpress theme files. Open you functions.php file and copy paste the following code in that file.


add_action('init', 'create_product');
 function create_product() {
 $product_args = array(
 'label' => __('Product'),
 'singular_label' => __('Product'),
 'public' => true,
 'show_ui' => true,
 'capability_type' => 'post',
 'hierarchical' => false,
 'rewrite' => true,
 'supports' => array('title', 'editor', 'thumbnail')
 );
 register_post_type('product',$product_args);
 }

How to use custom post type in wordpress
How to use custom post type in wordpress

The function register_post_type() accepts two arguments: the name we want to give our post type, and a list of arguments used to create that post type, which we put in an array called $args.

Using above code that code will add the product post type to wordpress panel.

Now you can add the meta fields to custom post type. Use the following code in file for add the meta fields. Custom meta fields function is available from quite some time. add_meta_box() function is very useful to adding custom fields to wordpress post.


<?php

 add_action("admin_init", "add_product");
 add_action('save_post', 'update_thumbnail_url');
 function add_product(){
 add_meta_box("product_details", "product Options", "product_options", "product", "normal", "low");
 }
 function product_options(){
 global $post;
 $custom = get_post_custom($post->ID);
 $thumbnail_url = $custom["thumbnail_url"][0];
 $product_info = $custom["product_info"][0];
 $product_infos = $custom["product_infos"][0];
 $video_code = $custom["video_code"][0];

?>
 <div id="product-options">
 <label>Thumbnail URL:</label><input size="100" name="thumbnail_url" value="<?php echo $thumbnail_url; ?>" /><br>
 <label>Product Info:</label><input size="100" name="product_info" value="<?php echo $product_info; ?>" /><br>
 <img src="<?php echo $product_infos; ?>"><br>
 <label>Video Code:</label><textarea cols="50" rows="5" name="video_code"><?php $video_code; ?></textarea>
 </div><!--end product-options-->
<?php
 }
 function update_thumbnail_url(){
 global $post;
 update_post_meta($post->ID, "thumbnail_url", $_POST["thumbnail_url"]);
 update_post_meta($post->ID, "product_info", $_POST["product_info"]);
 update_post_meta($post->ID, "video_code", $_POST["video_code"]);

 }
?>

Using following code you can see the product information in edit product page and you can able to see the all information in for edit. Admin will know which fields are available to edit.

How to use custom post type in wordpress
How to use custom post type in wordpress

<?php
add_action("manage_posts_custom_column",  "product_custom_columns");
add_filter("manage_edit-product_columns", "product_edit_columns");

function product_edit_columns($columns){
 $columns = array(
 "cb" => "<input type=\"checkbox\" />",
 "title" => "Product Title",
 "thumbnail_url" => "Thumbnail URL",
 "product_info" => "Product Info",
 "video_code" => "Video Code",
 );
 return $columns;
}
function product_custom_columns($column){
 global $post;
 switch ($column) {
 case "thumbnail_url":
 $custom = get_post_custom();
 echo $custom["thumbnail_url"][0];
 break;
 case "product_info":
 $custom = get_post_custom();
 echo $custom["product_info"][0];
 break;
 case "video_code":
 $custom = get_post_custom();
 echo $custom["video_code"][0];
 break;
 }
}

?>

Using custom post type and add meta tag you can develop very nice applications. Now I am going to show you how you can extract the custom posts in wordpress frontend.

Using wp_query you can easily extract product posts. In any category page or conditionally you can use following code.


$loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
 the_title();
the_content();
global $post;
 $custom = get_post_custom($post->ID);
echo $thumbnail_url = $custom["thumbnail_url"][0];
echo $product_info = $custom["product_info"][0];
echo $video_code = $custom["video_code"][0];
 echo '<div>';
 the_content();
 echo '</div>';
endwhile;

Or you can create the custom theme page using following code. Just create product.php page in your wordpress theme folder.Put following code in that file.


<?php

/*Template Name: Product*/

?>

<?php get_header(); ?>

<div id="container">

<div id="content" role="main">

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>

<?php $recent = new WP_Query('post_type=product&posts_per_page=10′); while($recent->have_posts()) : $recent->the_post();?>

<?php the_title( '<h2><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0′ ) . '" rel="bookmark">', '</a></h2>' ); ?>

<div>

<?php the_content(); ?>

<?php

the_content();
global $post;
$custom = get_post_custom($post->ID);
echo $thumbnail_url = $custom["thumbnail_url"][0];
echo $product_info = $custom["product_info"][0];
echo $video_code = $custom["video_code"][0];

?>

<?php wp_link_pages( array( 'before' => '<div>' . __( 'Pages:', 'wordpressapi' ), 'after' => '</div>' ) ); ?>

<?php edit_post_link( __( 'Edit', 'wordpressapi' ), '<span>', '</span>' ); ?>

</div><!– .entry-content –>

<?php comments_template( ", true ); ?>

<?php endwhile; ?>

</div><!– #content –>

</div><!– #container –>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Now create product page and product as template.

If you have any issues or doubts then write to me.

How to connect amazon instance through linux command prompt

There are many articles we can found for to connect to amazon ec2 machine though ssh. But all I found for windows. Using putty and putty key gen tool you can connect to amazon ec2 linux machine.

How to connect amazon instance through linux command prompt

How to connect amazon instance through linux command prompt
How to connect amazon instance through linux command prompt

If you are having the linux box and you want to connect to amazon ec2 machine then that is very easy. You just need to install the following package to connect to amazon ec2 machine.

Install the ec2-api-tools on linux or mac machine. use the following command.

# yum install ec2-api-tools

When you first try to create the amazon instance that time you need to create the key pair file. You got the .pem file as key pair file. That file is very important for connecting to amazon instance machines.

Keep your key pair file(.pem ) in safe location and dont give this file anyone. Go to directory where you kept the key pair file.

#ssh -i ec2-YOURKEY.pem root@ec2-51-18-49-55.compute-1.amazonaws.com

Using above command you can connect to amazon EC2 linux boxes.

how to install memcached on centos

We given steps for install memcached on centos. Memcached server is used for increase server performance and response time. Here we given the commands for installing memcached on centos.

how to install memcached on centos

I always need to install the memcached on my linux servers like fedora or centos. On fedora box installing the memcached is very easy through yum install. But Centos installing and using memcached is not so easy.

how to install memcached on centos
how to install memcached on centos

For my Ruby on Rails and PHP applications I always need to install the memcached on server. Here I am going to give you the steps for installing the memcached.

Very important note: you need to install the gcc compiler for memcached binary installation. Using the memcached with php installation you need the phpize and php-pecl-memcached installed. follow my steps and memcached binary installation.


# yum install gcc*
# cd /usr/src
# wget http://pecl.php.net/get/memcache-2.2.5.tgz
# tar zxvf memcache-2.2.5.tgz
# cd memcache-2.2.5
# phpize
# ./configure
# make
# make install

For checking the php.ini file path use following command.


php -i | grep php.ini

Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini

or your php.ini file will be following location


# vim /etc/php.ini

Put following line in that file
extension = “memcache.so”
Restart the apache server

# /etc/init.d/httpd restart

To check is memcache extension loaded in php, execute following command.

#php -i | grep memcache

After restarting the machine memcache need to restart. For that us ( Use this step for only Admin Adserver Box)

# vi /etc/rc.local

Put following contect in to rc.local file (file location – /etc/rc.local)

# memcached -d -p 11211 -u nobody -c 1024 -m 1024

How to install imagemagick binary on CentOS

For many application we need to install the imagemagick on Centos linux server. Many Ruby on rails and PHP applications need the support of imagemagick for image resizing.

How to install imagemagick binary on CentOS

 

How to install imagemagick binary on CentOS
How to install imagemagick binary on CentOS

We all the very traditional way of installing the application on linux machine which is as follows:

# yum install imagemagick

This command will not install the imagemagick on Centos properly. So use following commands for installing the imagemagick on centos

#yum install gcc*

#cd /tmp

# wget ftp://ftp.fifi.org/pub/ImageMagick/ImageMagick-6.6.1-10.tar.gz

# tar xzf ImageMagick-6.6.1-10.tar.gz

# cd ImageMagick-6.6.1-10

# ./configure

# make

# make install

After using the above commands imagemagick will be installed the properly on CentOS machine.

If you have any trouble or issues during installation then get back to me.

php encode and decode string with key

Many times php developers want to encode there php or important HTML,CSS or Javascript code. In this article I will show you the very simple encoding with using base64_encode method.

php encode and decode string with key

 

php encode and decode string with key
php encode and decode string with key

Here is working example.

<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
$str = 'This is an encoded string';
echo base64_encode($str);

echo base64_decode("VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==");
?></pre>
<pre>

you can create your own antilogarithm for encoding. For more information you can check the following URL

http://php.net/manual/en/function.base64-encode.php

Add custom background image support to wordpress

From wordpress 3.0, added new function to control the background image. For your theme if you want to add custom background image support to wordpress theme. From wordpress 3.0 release wordpress added new function to control the background color and image. For your theme if you want to add the background functionality then you need to very simple code in your functions.php file which you find in your wordpress theme folder.

Add custom background image support to wordpress

Open functions.php file and just copy paste the code.


add_custom_background();

For enabling the background for theme you need to open header.php file and just copy paste following code in the file.

<body class="<?php body_class() ?>">

For changing the background login to wordpress admin panel and goto appearance tab and click on background tab. From here you can able to change to background image or color.

Add custom background image support to wordpress
Add custom background image support to wordpress

how to create menu in wordpress themes

From wordpress 3.0 release wordpress launched the custom navigation Menu in wordpress admin panel. wordpress tutorial for, how to create menu in wordpress themes. Through drag and drop you can manage the menus. Using this menus are very easy for users.

how to create menu in wordpress themes

how to create menu in wordpress themes
how to create menu in wordpress themes

You can check wordpress admin section for managing the menus in wordpress theme.

In this article I will show you how to enable Custom menu for your wordpress theme.

If you want to create the one menu in wordpress theme then just open the functions.php file and put following code in that file.


add_theme_support( 'menus' );

If you want to create or use the multiple menus in wordpress theme then just open the functions.php file and put following code in that file.


add_action( 'init', 'register_my_menus' );

function register_my_menus() {
 register_nav_menus(
 array(
 'primary-menu' => __( 'Main Menu' ),
 'secondary-menu' => __( 'Top Menu' ),
 'tertiary-menu' => __( 'Footer Menu' )
 )
 );
}

After this adding code in functions.php file you need to open the header.php and footer.php file.

For single menu you need to add following code in header.php file.


<?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'container_class' => 'menu-header' ) ); ?>

For multiple menu you need to add following code in header.php or footer.php file

# Following code for Top Menu


wp_nav_menu( array( 'theme_location' => 'secondary-menu', 'sort_column' => 'menu_order', 'container_class' => 'nav' ) );

#Following code for Main Menu


&lt;?php wp_nav_menu( array( 'theme_location' => 'primary-menu', 'sort_column' => 'menu_order', 'container_class' => 'nav' ) ); ?>

#Following code for Footer Menu


&lt;?php wp_nav_menu( array( 'theme_location' => 'tertiary-menu' ) ); ?>

Above code will give you the more control over the wordpress theme. If you have any doubts or questions then please do write to me.

mysql sleep processes issue solved

I faced the sleep query issue sometimes.  Many times that kills the server. When ever you are using dedicated virtual hosting server that time you need to me very careful how you are setting up the apache and mysql. we solved mysql sleep processes issue

mysql sleep processes issue solved

mysql sleep processes issue solved
mysql sleep processes issue solved

I found some major reasons for mysql sleep processes. Here I am giving some reasons:

[viral-lock message=”Reasons and Solution is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]

1. apache requests increase
2. mysql queries increase
3. mysql slow queries increase
4. apache connections start to wait on slow mysql queries
5. apache connections take longer to close
6. more apache connections are opened
7. with each apache request a new sleeping mysql connection is made
8. mysql & apache reach max_connections
9. server slows to a crawl

[/viral-lock]

Using linux top command you can check the load average and which process is taking so much memory of your server. If you saw mysqld is taking much memory of server then you should check using following mysql commands:

> show full processlist;

using this command you can check the mysql processes. Which sql queries being fired on mysql server. If you found so much sleep processes then you should check your mysql variables and settings. If so much mysql queries being fired on specific table then you should change the table storage engine type.

Using following command you can change the storage engine type.
> ALTER TABLE tablename ENGINE = MYISAM;

MYISAM storage engine type is faster then inodb. you can create the mediator tables also for big size table to handing a load of table.

Then major change for solving the issue of sleep processes is, you should change the wait_timeout variable. Default value is 2800 seconds.

mysql> show variables;

you can change the setting using following  mysql command. Best value is 60 second need to be set for wait timeout.
mysql> show variables like ‘wait_timeout’;

mysql> set global wait_timeout=60;

mysql>show variables like ‘wait_timeout’;

After doing above changes you can check the mysql processlist. If you are still facing issues with mysql then please write to me.