Setup an Apache Reverse Proxy Server on Ubuntu 14.04


In my last post, I demonstrated how we can set up an Apache Forward Proxy Server on Ubuntu 14.04. So, this post will talk about everything you need to set up an Apache Reverse Proxy Server.

Difference between Forward and Reverse Proxy.

Before I start this tutorial, we must first understand the difference between Forward and Reverse Proxy. Since my blog is all about simple explanation, I will keep things simple & informative 🙂

Forward Proxy server is your more obvious kind of proxy where you access a remote server, like Google or Facebook or another remote server in your network such as Jenkins, via a proxy server. It means, data packets flow like this.

Client(aka you) –> Forward Proxy server –> Remote server(aka Google).

Forward implies that your proxy server sits in front of your remote server. You need to configure your client to use Forward Proxy server. Your remote server will see IP of your proxy server & knows nothing about client’s existence.

Reverse Proxy is a different concept. Here you also access your remote server via a proxy server but you don’t specify IP or hostname of your remote server. You enter IP/hostname of your Reverse proxy server which redirects your request to the remote server, based on its configuration. Data packets flow in the similar manner, but you only invoke your Reverse Proxy server here as opposed to invoking your remote server.

Suppose you have a Jenkins server running on port 8080. You want to access this server but you don’t want to expose its port. You setup an Apache Reverse Proxy Server & tell it to redirect all requests landing on port 80 (Apache’s default) to Jenkins server which is running on port 8080. Since its default port, you just enter IP/hostname of your Reverse Proxy server in your browser & you will end up seeing Jenkins GUI 😉 You don’t need to configure any client at all here because you are entering Reverse Proxy server’s IP/hostname only.

Armed with some information, lets begin this tutorial 🙂

Lab Description : –

  • Reverse Proxy Server – An Ubuntu 14.04 Server running Apache with IP 192.168.0.51
  • Client  – An Ubuntu 14.04 Server with IP 192.168.0.50
  • Remote Server – An Ubuntu 14.04 Server with IP 192.168.0.50. This server runs my Jenkins, so I will be accessing Jenkins from my client via proxy server. Note that I am using same host for client & remote server. This is because my request will go to Reverse Proxy Server only & it will redirect that request to Jenkins which runs on the same host.

Steps to Perform : –

Configure Reverse Proxy Server (192.168.0.51).

1. Install core product.

Install Apache, if not already done. It is as simple as issuing –

root@shashank-reverse-proxy-server:/home/shashank# apt-get install-y apache2 apache2-doc apache2-utils

2. Install necessary modules.

Issue below command to install modules required for proxy server.

root@shashank-reverse-proxy-server:/home/shashank# apt-get installlibapache2-mod-proxy-html libxml2-dev

3. Enable Apache modules.

Issue below command to enable all the required Apache modules.

root@shashank-reverse-proxy-server:/home/shashank# a2enmod proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

4. Configure proxy configuration file.

We will now create an Apache proxy configuration file that will hold information required for proxying. Start with creating a file like this.

root@shashank-reverse-proxy-server:/home/shashank# vim /etc/apache2/mods-available/mod_reverse_proxy.conf

Please check my GitHub gist to see the contents of this file. HTML tags are interfering with the tags in configuration file. You can see that nothing much is happening here except enabling the proxy.

If you want to run Apache on its default port, its alright. Otherwise you may wish to edit /etc/apache2/ports.conf file. Whatever port you define here will be used to access your remote server in the form of IP/hostname of Reverse Proxy server:port#.

5. Define a Virtual Host.

Its now time to define a Virtual Host which is a separate instance of your web-server(remember you can host multiple sites on a single Apache server). We are defining it to enable more fine-grained logs & redirection for remote server. Start with backing up the original default Virtual Host.

root@shashank-reverse-proxy-server:/home/shashank# cp -p /etc/apache2/sites-enabled/000-default.conf /etc/apache2/sites-enabled/000-default.conf.orig

Now rename 000-default.conf to apache_reverse_proxy.conf to avoid confusion.

Now edit this /etc/apache2/sites-enabled/apache_reverse_proxy.conf file to define logs location & port. You can see that I am redirecting all incoming HTTP requests to my remote Jenkins server which is running on port 8080.

Please check my GitHub gist to see the contents of this file.

6. Enable the Virtual Host.

Time to enable our newly created Virtual Host.

root@shashank-reverse-proxy-server:/home/shashank# a2ensiteapache_reverse_proxy.conf Enabling site reverse-proxy. To activate the new configuration, you need to run: service apache2 reload root@shashank-reverse-proxy-server:/home/shashank# service apache2 reload * Reloading web server apache2 *

7. Restart Apache.

Configuration is now done & we must restart Apache to load these new settings.

If everything is configured correctly, you will now have a working Reverse Proxy Server.

To test it, log on to your client server 192.168.0.50 & open your browser. Now enter just the IP address of your Reverse Proxy server 192.168.0.51. You will see Jenkins GUI 🙂 Since I am running Apache on its default port 80, I only used192.168.0.51. If it was running on some other port, I would have used 192.168.0.51:port#. See the screenshot below to see Reverse Proxy in action 😉

Jenkins_behind_Reverse_Proxy_server.png

If you stop Apache service & retry opening Jenkins, you will see that its not loading & asks you to check Proxy configuration 😉

As always, you are most welcome if you have suggestions/feedback or you need more information 🙂

How To Setup An Apache Forward Proxy Server on Ubuntu 14.04


Introduction : –

A Forward Proxy Server is a server that sits between you, aka client, and your remote server. Lets put it in a simple way 🙂

Lets say you want to access Facebook from your laptop using your favorite browser. Your browser is a client here. Facebook obviously runs on a server 😉 Now, all HTTP requests made from your browser to Facebook will contain your laptop’s IP address as well. But you don’t want your IP address to be tracked. What you will do now?

Yes, the answer is setting up a Forward Proxy Server. This proxy server will sit between you & Facebook server. Whatever HTTP requests your browser will initiate will be relayed/proxied via this proxy server. Data packets flow like this. Your laptop –> proxy server –> Facebook server.

It means, Facebook will see that the request came from the proxy server & it will never know that it actually originated from your laptop.

It is just a simple explanation of Forward Proxy Server. There are many other uses & explanations. But I tend to keep things simple 😉

Lab Description : –

  • Forward Proxy Server – An Ubuntu 14.04 Server running Apache with IP 192.168.0.62
  • Client  – An Ubuntu 14.04 Server with IP 192.168.0.51
  • Remote Server : – An Ubuntu 14.04 Server with IP 192.168.0.50. This server runs my Jenkins, so I will be accessing Jenkins from my client via proxy server.

Steps to Perform : –

Configure Forward Proxy Server.

1. Install core product.

Install Apache, if not already done. It is as simple as issuing –

root@shashank-forward-proxy-server:/home/shashank# apt-get install-y apache2 apache2-doc apache2-utils

2. Install necessary modules.

Issue below command to install modules required for proxy server.

root@shashank-forward-proxy-server:/home/shashank# apt-get installlibapache2-mod-proxy-html libxml2-dev

3. Enable Apache modules.

Issue below command to enable all the required Apache modules.

root@shashank-forward-proxy-server:/home/shashank# a2enmod proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

4. Configure proxy configuration file.

We will now create an Apache proxy configuration file that will hold information required for proxying. Start with creating a file like this.

root@shashank-forward-proxy-server:/home/shashank# vim /etc/apache2/mods-available/proxy.conf

Please check my GitHub gist to see the contents of this file. HTML tags are interfering with the tags in configuration file. You can see that nothing much is happening here except enabling the proxy.

5. Define port for proxy server.

Now we need to define the port on which our proxy server must run. Issue this command after backing up the original file.

root@shashank-forward-proxy-server:/home/shashank# sed -i -e 's/80/8889/g' /etc/apache2/ports.conf

You can see that I have replaced default port 80 with 8889. Choose any port that you like & is available.

6. Define a Virtual Host.

Its now time to define a Virtual Host which is a separate instance of your web-server(remember you can host multiple sites on a single Apache server). We are defining it to enable more fine-grained logs & port. Start with backing up the original default Virtual Host.

root@shashank-forward-proxy-server:/home/shashank# cp -p /etc/apache2/sites-enabled/000-default.conf /etc/apache2/sites-enabled/000-default.conf.orig

Now edit this /etc/apache2/sites-enabled/000-default.conf file to define logs location & port. Here, I am running it on the same port 8889 as this is my only instance.

Please check my GitHub gist to see the contents of this file.

As you can see, we have defined the location for logs specific to proxy.

7. Enable the Virtual Host.

Time to enable our newly created Virtual Host.

root@shashank-forward-proxy-server:/home/shashank# a2ensite 000-default.conf

8. Restart Apache.

Configuration is now done & we must restart Apache to load these new settings.

root@shashank-forward-proxy-server:/home/shashank# service apache2 restart
 * Restarting web server apache2 [Fri Jun 23 09:09:32.982307 2017] [proxy_html:notice] [pid 2940:tid 140143966525312] AH01425: I18n support in mod_proxy_html requires mod_xml2enc. Without it, non-ASCII characters in proxied pages are likely to display incorrectly.
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using node2.shashank.com. Set the 'ServerName' directive globally to suppress this message

With a success message, you are confident that your Apache configuration is correct 🙂 Above is just a warning & not an error, so no need to worry 😉

Lets move on to client-side configuration.

Client Side Configuration : –

With a working Apache Forward Proxy Server configuration, lets move on to our client machine & configure it to use our proxy server. For this, log-in to the machine & go to System Settings. Then select Network & then Proxy.

Enter your HTTP proxy server IP or FQDN or hostname & the port. Remember we configured our proxy server to run on port 8889.

Configuring_Client_to_use_Apache_Forward_Proxy_Server-Shashank_Srivastava.png

Test proxy connections.

You are all set now 🙂 Time to test the settings. Lets now open our browser & try to access Facebook & also Jenkins on a remote server (IP 192.168.0.50. See Introduction) in the same network. If your configuration is correct, you will be able to browse Facebook or internet without any issue. You will also be able to access your Jenkins server. You can check your proxy in action in below logs. Remember we had configured log location in step # above. You need to log-in to your proxy server & check the log file which happens to be /var/log/apache2/access_forward_proxy.log . If your location is different, make sure you check that file.

You can see that requests made from client 192.168.0.51 to remote server 192.168.0.50 are proxying through our proxy server.

192.168.0.51 - - [23/Jun/2017:09:33:17 +0530] "GET http://192.168.0.50:8080/static/50cbf35e/images/16x16/warning.png HTTP/1.1" 200 761 "http://192.168.0.50:8080/static/50cbf35e/css/style.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
192.168.0.51 - - [23/Jun/2017:09:33:17 +0530] "GET http://192.168.0.50:8080/static/50cbf35e/images/16x16/error.png HTTP/1.1" 200 817 "http://192.168.0.50:8080/static/50cbf35e/css/style.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
192.168.0.51 - - [23/Jun/2017:09:33:17 +0530] "GET http://192.168.0.50:8080/static/50cbf35e/images/top-sticker-bottom-edge.png HTTP/1.1" 200 605 "http://192.168.0.50:8080/static/50cbf35e/css/style.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
192.168.0.51 - - [23/Jun/2017:09:33:03 +0530] "CONNECT fonts.gstatic.com:443 HTTP/1.1" 200 4806 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
192.168.0.51 - - [23/Jun/2017:09:33:17 +0530] "GET http://192.168.0.50:8080/opensearch.xml HTTP/1.1" 200 6997 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"

I hope you found this post interesting, informative & easy 🙂 Do let me know if it needs improvements or you have suggestions 🙂

Bash Shell Script To Create A Rich, Colorful Server Health Report(in HTML)


As you know,  my previous shell script produces an HTML Server Health Report displaying all vital stats in a plain format & I thought its magical to have a shell script create an HTML report even though it was a rather simple looking report 😉 Then I wrote a web-app that helps you track how much money you have saved & came up with the idea to enhance my script to output a rich, vibrant, vividly colored HTML report that has interactive 3D charts & other colorful visual elements 🙂 Sneak a peek below!

You can grab the script from my GitHub gist page.

Server-Health-Report-Shashank_Srivastava.png

So, I modified my script & made it fetch more server data and display that data in different tables & panels. These tables & panels include : –

Directories that eat up most of your disk space.

Server-Health-Report-Shashank_Srivastava.png

Dynamic table showing the directories that take up most of your disk-space.

Top Memory consuming processes.

Server-Health-Report-Shashank_Srivastava.png

Dynamic table displaying Top Memory consuming processes.

Top CPU consuming processes.

Server-Health-Report-Shashank_Srivastava.png

Dynamic table displaying Top CPU consuming processes.

2 Speedometers displaying # of processes running & # of logged in users.

Server-Health-Report-Shashank_Srivastava.png

Speedometer 🙂

A bars system that displays the resources utilisation (RAM/CPU/Filesystem/INodes) & these bars change their color to red if threshold is crossed 🙂

Server-Health-Report-Shashank_Srivastava.png

Bars displaying vital system stats.

3D interactive pie-chart showing the break-up of filesystem utilisation.

Server-Health-Report-Shashank_Srivastava.png

3D chart with break-up of filesystem usage.

How To Receive Emails From Your PHP OpenShift Application Using Swift Mailer & GMail


There are times when we need emails to be sent/received from our PHP applications hosted on OpenShift. My particular example is based on a feedback form that I have put on my own PHP based web-application hosted on OpenShift http://www.howmuchisaved.in. Using this form, I can receive email whenever users submit their feedback to me. If your applications is hosted on your own server, you can easily setup Postfix to start receiving mails but things start to get tricky when you have little to no control on the web-server which runs your application. OpenShift doesn’t allow you to configure Postfix or any such utilities. It even doesn’t give you root access to install & configure dependencies. So, you are left with very little options. And this is where Swift Mailer comes to rescue. In this tutorial I will explain how you can leverage Swift Mailer PHP library to be able to receive mails. Please note that this tutorial can be followed for other restrictive hosting solutions as well.

Requirements : –

For this tutorial, you will need one GMail account (more on it below) & one PHP application hosted on OpenShift or any cloud platform.

Steps to be performed : –

Configure Google Security settings

Since we are using GMail as our SMTP, all emails will be delivered/relayed via smtp.gmail.com. By default, Google doesn’t allow less-secure apps (such as your OpenShift app) to access your account. So, go to https://www.google.com/settings/security/lesssecureapps and turn it on. Its better to create a new Google account & turn this setting on for that particular account. Choice is yours, so act accordingly.

Download Swift Mailer PHP Library

Download it from here https://github.com/swiftmailer/swiftmailer & place it inside your project directory.

Or if you have git installed on your machine, you can always use git clone https://github.com/swiftmailer/swiftmailer inside your project directory. This will create a new directory inside your project. Rename it so that its easy to reference Swift Mailer inside your code. I renamed mine as swiftmailer.

Edit PHP code

Now, with Swift Mailer library in place, edit your PHP script that handles e-mail functionality. Below is the sample code snippet from my GitHub repository’s file.

https://github.com/shashank-ssriva/HowMuchISaved/blob/openshift-version/howmuchisaved/send_feedback_mail.php

You may fork or download my entire project if you so wish 🙂 This version is fully functional and is already hosted on OpenShift (as told in introduction above).

require_once 'swiftmailer/lib/swift_required.php';
      //allow less secured app in Gmail settings for this to work.
      //Also use port 465 and ssl if it doesn't work.
      $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, "tls")
      ->setUsername('your gmail username')
      ->setPassword('your gmail password');

You can see in the snippet above how you need to organise your Swift Mailer directory. You also need to enter your GMail credentials there.

Test your application

After making changes to the code, fire up your application in a browser & check if you received email from this page or not. Please note the line #22 in above
script. It mentions the email-address where you will be receiving e-mails from your application. Change this to yours if not already done.

That’s it 🙂 If everything has been configured correctly, you will start to receive e-mails from this application. You may use my repository for fully functional application & its code.

Create a Server Health Report (HTML) Using Shell Script


Shell scripts are insanely powerful & convenient. We all know it 😉 Much of the beauty in shell scripts lies in the way they can be used to automate many aspects of System Administration. As a SysAdmin, you might have been asked to prepare health-reports on a regular basis. Today, I wrote one such script that will generate an HTML health-report containing some vital system information. Lets see how it works 🙂

Lab Description : –

Ubuntu 14.04 Server. Environment : – Bash shell

Instructions : –

Download or clone my GitHub repository from below location.

https://github.com/shashank-ssriva/Linux-Server-HTML-Health-Report-Using-Shell-Script

Place the syshealth.sh file anywhere you want. I prefer keeping it under my home-directory but you may keep it anywhere.

Make it executable (if not already).

You may either run/execute it manually or you may also put it in a CRON job. I have chosen to generate the report twice a day, but its entirely upto you 🙂

Video Tutorial : –

To see the script in action, watch the video below on my YouTube Channel.

Additional Notes : –

I have kept the script & report minimal since I wrote it today only. You may customize it further so as to suit your needs. Sky is the limit 😉

Setup MySQL Cluster/Load-balancing Using HAProxy


I have already explained how to setup streaming replication in MySQL in my previous posts mentioned below. I have also showed you how you can load-balance Apache web-servers using HAproxy.

How To Setup Streaming Replication In MySQL – Slave Node

How To Setup Streaming Replication In MySQL – Master Node

In this post, I will demonstrate how we can put our MySQL cluster behind an HAProxy load-balancer so that our database continues to run even if master database node crashes. This post is about master-slave load-balancing. So, data will be written to master only but retrieved from any node. I will write another post on master-master replication later. Lets start now 🙂

Lab Description : –

1 Load-balancer –

An Ubuntu 14.04 server running HAProxy 1.4.24. IP Address = 192.168.0.50

2 MySQL Database nodes (from previous posts, they are already under streaming replication)-

  • Master Node – 192.168.0.31 running MySQL 5.6.17
  • Slave Node – 192.168.0.32 running MySQL 5.6.17

Steps to be performed : –

1. Install HAProxy

root@haproxy-server:/home/shashank# apt-get install haproxy

This will install HAProxy, an open source load-balancer on our Ubuntu server.

2. Install MySQL client

Now we will need to install mysql-client on Ubuntu server to connect to our databases. So, issue below command to install it.

root@haproxy-server:/home/shashank# apt-get install mysql-client

Note that if you already installed MySQL on this server before, you may skip this step as client will be already present. You may issue mysql command to check.

3. Create users on MySQL servers.

Now we need to add 2 database users to connect to our MySQL databases servers from HAProxy Ubuntu server. Fail-over needs root access to database, hence one of these users will have equivalent privileges. You may continue with root but that will require more configurations and its always safe to have a user other than root. Note that below queries have to be run on both database nodes.

E:\wamp\bin\mysql\mysql5.6.17\bin>mysql -u root -p -e "INSERT INTO mysql.user (Host,User) values ('192.168.0.50','haproxy_test'); FLUSH PRIVILEGES;"
Enter password: *****

E:\wamp\bin\mysql\mysql5.6.17\bin>mysql -u root -p -e "GRANT ALL PRIVILEGES ON *.* TO 'haproxy_root'@'192.168.0.50' IDENTIFIED BY 'haproxy' WITH GRANT OPTION; FLUSH PRIVILEGES;"
Enter password: *****

You can see that haproxy_root user has root access & haproxy_test is created just to login to database.

4. Configure HAProxy

Its time to edit HAProxy’s configuration. By default, its disabled. So, edit the file /etc/default/haproxy & change ENABLED=0 to ENABLED=1. Now, backup the existing HAProxy configuration file /etc/haproxy/haproxy.cfg & edit it with below contents. I have put comments wherever necessary.

global
log 127.0.0.1 local0 notice
user haproxy
group haproxy

defaults
log global
retries 2
timeout connect 3000
timeout server 5000
timeout client 5000

listen mysql-cluster #name of your mysql cluster.
bind 0.0.0.0:3306
mode tcp
option mysql-check user haproxy_check #db user created in last step
balance roundrobin
server host_name 1 192.168.0.32:3306 check #hostname & IP:port of DB node1
server host_name 192.168.0.31:3306 check  #hostname & IP:port of DB node2

listen 0.0.0.0:8090 #port to bind HAProxy's web UI to.
bind 192.168.0.50:8090
mode http
stats enable
stats uri /
stats realm Strictly\ Private
stats auth user1:PASSWORD #user:password for authentication while opening web UI
stats auth user2:PASSWORD

frontend LB #optional & can be left
bind 192.168.0.50:8090

One main point to remember is to bind HAProxy to proper host & port. Since my web-application runs on a different server, I used listen 0.0.0.0:3306 in cluster properties above. HAProxy doesn’t have special properties for MySQL unlike Web-server. So I chose tcp above. If there are errors in your HAProxy configuration, you will see errors like below on starting haproxy service.

root@haproxy-server:/home/shashank# service haproxy start
* Starting haproxy haproxy [ALERT] 243/081515 (22114) : parsing [/etc/haproxy/haproxy.cfg:22] : 'bind' expects [addr1]:port1[-end1]{,[addr]:port[-end]}... as arguments.
[ALERT] 243/081515 (22114) : Error(s) found in configuration file : /etc/haproxy/haproxy.cfg
[ALERT] 243/081515 (22114) : config : proxy '192.168.0.50:8080' has no listen address. Please either specify a valid address on the <listen> line, or use the <bind> keyword.
[ALERT] 243/081515 (22114) : Fatal errors found in configuration.

It was partly because I had earlier used port 8080 for web UI but it was already in use. So I used 8090. Also, I had bound cluster to 127.0.0.1 but it should have been 0.0.0.0 or public IP of application/web-server.

Once this is done/fixed, start the service. It will start without any error.

5. Test load-balancer.

If you performed the steps correctly, you can now see your MySQL cluster being accessed by HAProxy server in a round-robin manner i.e. one by one 🙂 You have to use 127.0.0.1 here & not the public IP or hostname. You may also point your browser to IP_address of haproxy server:8090 or any port you specified in configuration above to see the web UI. Credentials will be what you mentioned in its configuration.

mysql_cluster

root@haproxy-server:/home/shashank# mysql -h 127.0.0.1 -u haproxy_root -p -e "SHOW DATABASES"
Enter password:
+--------------------+
| Database           |
+--------------------+
| information_schema |
| asset              |
| mysql              |
| performance_schema |
| test               |
| testdb             |
+--------------------+

Great 🙂 You can access your cluster from load-balancer, as you can see above 🙂 Now, its time to see which node is being accessed. So, issue below command on load-balancer server 2-3 times & you will see server-ids in round-robbin manner 🙂

root@shashank-server:/home/shashank# mysql -h 127.0.0.1 -u haproxy_root -p -e "show variables like 'server_id'"
Enter password:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 2     |
+---------------+-------+
root@haproxy-server:/home/shashank# mysql -h 127.0.0.1 -u haproxy_root -p -e "show variables like 'server_id'"
Enter password:
root@haproxy-server:/home/shashank# mysql -h 127.0.0.1 -u haproxy_root -p -e "show variables like 'server_id'"
Enter password:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 1     |
+---------------+-------+

6. Test your application

Now that basic testing has been done, now its time to test our setup in live scenario. To do this, stop mysql service on any database node & execute the same command(that you ran above) on load-balancer. You will see server-id of the other node every time you run this. Now, bring up the service and stop it on other node. Again run the same query & see the result 🙂

Now, change the application code where you have hard-coded database connection string & replace that name/IP with load-balancer IP 🙂 Check your application now by trying to read from the database. You will see that you can access the data even when one of your DB nodes is down 🙂

With this, you have successfully setup a MySQL cluster & load-balancing 🙂 See you soon!

How To Setup Streaming Replication In MySQL – Slave Node


In my last post, you read about configuring the master node. Here, you will learn how you can configure slave for streaming replication. Lets start this tutorial 🙂

Create the same database as on master.

As you know, our example slave node has IP 192.168.0.32 & that will run our replicated database. So, create the same database here.

mysql> create database your_db_name;

Import the dump file to populate data.

Now, exit the mysql prompt & import the dump file that you copied from master node. This will populate our database with the data from master.

C:\Program Files\MySQL\MySQL Server 5.6\bin>mysql -uroot -p asset < C:\your_db_name.sql
Enter password: *****

Edit my.ini or my.cnf file.

Here we will edit the configuration file to indicate which one is our master & similar settings. Enter below details to your file. Read the file carefully & make changes accordingly. datadir is optional. Save the file & restart MySQL. On Windows, you need to go to Services & restart MySQL service. After that, you will see the data populated from dump file.

[mysqld]
server-id=2
relay-log-index=slave-relay-bin.index
relay-log=slave-relay-bin
datadir=C:\Program Files\MySQL\MySQL Server 5.6\data
replicate-do-db=your_db_name
master-host=192.168.0.31
master-user=repl_user
master-password=PASSWORD

Stop slave.

Login to your MySQL & issue below to stop the slave.

mysql> stop slave;
Query OK, 0 rows affected (0.00 sec)

Configure slave to start replication from master. 

Issue below query to start the replication process. Please change the values accordingly. In the last 2 properties, use the values that you noted down while configuring master. Its the File & Value property that you need to enter from that output. After this, start your slave.

mysql> CHANGE MASTER TO
-> MASTER_HOST='192.168.0.31',
-> MASTER_USER='repl_user',
-> MASTER_PASSWORD='PASSWORD',
-> MASTER_LOG_FILE='mysql-bin.000003',
-> MASTER_LOG_POS=120;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

Now you are done 🙂 Just create new tables or add record in your master database. All that will be mirrored to your slave database 🙂 Check it for yourself!