How to Set Up an Email Server with Postfix, Dovecot and Roundcube on Ubuntu 18.04

Postfix is a Mail Transfer Agent(Agent). It is a powerful open-source application that is capable of receiving and sending emails.

Dovecot is a free open-source POP3 and IMAP server that delivers and retrieves emails to local mailboxes on the Linux system.

Roundcube is a web-based email client that works pretty well with Postfix and Dovecot.

While utilizing the POP and IMAP protocol on Dovecot, Roundcube can read emails stored by Dovecot on virtual mailboxes.

At the same time, Roundcube can submit emails to Postfix using the SMTP protocol.

So by harnessing the power of three open source applications (Postfix, Dovecot, and Roundcube), you can create a fully functional send/receive email server.

This is a comprehensive guide for setting up an email server with Postfix, Dovecot, and Roundcube on Ubuntu 18.04 server.

Note: For a better experience with Postfix, Sign up with Digital Ocean and get up to $100 free trial credit. We recommend Digital Ocean because they allow outbound and inbound traffic to port 25.

Prerequisites

To follow along with this guide, you will require the following:

  1. A new VPS(Virtual Private Server) account. Sign up with Digital Ocean and enjoy up to $100 worth of free trial credit.
  2. A domain name(e.g. example.com)
  3. A VPS instance running Ubuntu 18.04 as the operating system
  4. A non-root user that can perform sudo tasks

Step 1: Configuring DNS Server

Your email server must have a fully qualified domain name.

To set up this, you must point the A record of your domain to the public IP address associated with your VPS instance.

You must also set MX records on your domain name DNS records editor. This is done from the control panel of your VPS provider.

Then, you need to change the hostname of your server.

To edit the server hostname, open the /etc/hostname file and change the name to something appropriate e.g., mail

$ sudo nano /etc/hostname

Save the file by pressing CTRL+X, Y and, Enter

The next step is editing the hosts’ file /etc/hosts. Open the file using nano text editor.

$ sudo nano /etc/hosts

Make sure you have the below two entries at the top of the file. Replace example.com with your domain name.

127.0.0.1    localhost
127.0.1.1    mail.example.com mail

Reboot the system

$ sudo reboot

Step 2: Installing Apache Web Server

With the server name and DNS records configured, we will go ahead and install Apache web server.

Apache is primarily needed by Roundcube email client for it to run from a browser like Google Chrome.

Install Apache.

$ sudo apt-get update
$ sudo apt-get install apache2

Press Y and hit Enter when prompted to confirm the installation.

Also, make sure the Mod_Rewrite module is enabled. This will be required for Roundcube to work:

$ sudo a2enmod rewrite

Restart Apache.

$ sudo systemctl restart apache2

Step 3: Installing MySQL Database Server

Roundcube requires MySQL for it to work, so we are going to install the database server.

$ sudo apt-get install mysql-server

Press Y and Enter to confirm the installation.

Next, run the command below to secure MySQL database server.

$ sudo mysql_secure_installation

Step 3: Installing Let’s Encrypt Certificate

In order for the mail server to use SSL, we need to install an SSL certificate.

To do this, run the command below and remember to replace example.com with the exact domain name that you intend to use with your mail server.

$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache
$ sudo certbot --apache -d example.com -d www.example.com

Step 3: Installing PHP Scripting Language

Roundcube is written in PHP. As such, we need to install PHP together with all associated modules required by Roundcube.

$ sudo apt-get install php libapache2-mod-php php-mysql

Again, press Y when prompted to confirm the installation and hit Enter to continue.

Step 4: Installing Postfix MTA

Next, we are going to install Postfix Mail Transfer Agent (MTA). To do this, run the command below:

$ sudo apt-get install postfix

Press Y and hit Enter when prompted to confirm the installation.

On the next screen, hit TAB then Enter to continue.

You will be prompted to select the mail server configuration type. Choose Internet Site and press TAB and Enter to continue.

On the next screen, you should enter the name of your domain without the ‘www’ part.

So, if your domain name is www.example.com, enter example.com on the system mail name field and hit Tab and Enter to continue.

After a few seconds, Postfix will be successfully installed on your Ubuntu 18.04 server

Step 5: Configuring Postfix

Postfix MTA is a very powerful and secure out-of-the-box. However, it requires a few configurations for it to work with Ubuntu 18.04 and Dovecot.

The main Postfix configuration file is located at /etc/postfix/main.cf.

We will back up this file before editing it by running the command below.

$ sudo mv /etc/postfix/main.cf /etc/postfix/main.cf.bk

This ensures that we can go back to the default settings in case we mess up with the Postfix configuration.

Next, we can create a new Postfix configuration file using nano text editor:

$ sudo nano /etc/postfix/main.cf

Paste the below information on the file and remember to replace example.com with your domain name.

# GENERAL SETTINGS

smtpd_banner = $myhostname ESMTP $mail_name
biff = no
append_dot_mydomain = no
readme_directory = no

# SMTP SETTINGS 

smtp_use_tls=yes
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# SMTPD SETTINGS 

smtpd_use_tls=yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_tls_cert_file=/etc/letsencrypt/live/example.com/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/example.com/privkey.pem
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated,  reject_unauth_destination

# SASL SETTINGS

smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

# VIRTUAL MAIL BOX AND LMTP SETTINGS

virtual_transport = lmtp:unix:private/dovecot-lmtp
virtual_mailbox_domains = /etc/postfix/virtual_mailbox_domains



# OTHER SETTINGS

myhostname = mail.example.com
myorigin = /etc/mailname
mydestination =  localhost.$mydomain, localhost
relayhost = 
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases

Once you add the settings above, save and close the file.

Step 6: Creating Virtual Mail Box Domains

Our Postfix configuration file that we created above instructed the mail server to look for virtual mailbox domains from the /etc/postfix/virtual_mailbox_domains file.

We need to add the domains that we intend to use with the mail server on this file. You can add as many domains as you want.

To keep things simple, we are adding the example.com domain.

Open the file:

$ sudo nano /etc/postfix/virtual_mailbox_domains

Then, add the entry below. Please note, the entry MUST be in two parts as shown below.

example.com #domain

Save and close the file when done.

Since Postfix is not configured to read plain text files, we will convert the file to a format that it can understand using the command below:

$ sudo postmap /etc/postfix/virtual_mailbox_domains

Remember, you must run that command each time you edit the /etc/postfix/virtual_mailbox_domains file.

The next step is setting up the Postfix’s master configuration file /etc/postfix/master.cf.

Open the file using nano text editor.

$ sudo nano /etc/postfix/master.cf

Look for the line below.

#submission inet n       -       y       -       -       smtpd

Then, remove the leading # symbol to uncomment it:

submission inet n       -       y       -       -       smtpd

When done, save the file and close it.

Step 7: Installing Dovecot on Ubuntu 18.04

Next, we will install Dovecot and all associated packages necessary for running IMAP, POP and LMTP protocol.

$ sudo apt-get install dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd

Step 8: Configuring Dovecot mail_location

In order for Dovecot to communicate with Postfix and our virtual mailbox domains, we need to make a few changes to its configuration files.

We will start off by editing the /etc/dovecot/conf.d/10-mail.conf file

$ sudo nano /etc/dovecot/conf.d/10-mail.conf

Locate the mail_location parameter :

mail_location = mbox:~/mail:INBOX=/var/mail/%u

Then, change its value as shown below :

mail_location = maildir:/var/mail/vhosts/%d/%n

Save and close the file

In a nutshell, we have instructed Dovecot to look for mails on the /var/mail/vhosts directory.

So for Dovecot to work, we need to create a sub-directory for each domain we intend to use with our email server.

Step 9: Creating Dovecot vhosts Directory

Let’s create the vhosts directory first:

$ sudo mkdir /var/mail/vhosts

Then we can go ahead and create the sub-directory for our domain name.

$ sudo mkdir /var/mail/vhosts/example.com

If you have multiple domains, repeat the command above while replacing the last part of the directory name(example.com) with the name of each domain.

Step 10: Creating Dovecot vmail User and Group

The next step is creating a vmail user and a group. We will also assign the user access to the vhosts directories that we created above.

First, let’s create the group:

$ sudo groupadd -g 5000 vmail

Next, we can create a vmail user and the same to the group that we have created above:

$ sudo useradd -r -g vmail -u 5000 vmail -d /var/mail/vhosts -c "virtual mail user"

Then, we need to assign the ownership of the directories to the vmail user.

$ sudo chown -R vmail:vmail /var/mail/vhosts/

Step 11: Enabling Dovecot for Secure POP3 and IMAP Services

Next we are going to edit the /etc/dovecot/conf.d/10-master.conf file and enable IMAPs and POP3 secure services.

First, open the file

$ sudo nano /etc/dovecot/conf.d/10-master.conf

Then, find the entries below.

inet_listener imaps {
    #port = 993
    #ssl = yes
  }

Change them to:

inet_listener imaps {

    port = 993
    ssl = yes
  }

On the same file, locate the below content.

inet_listener pop3s {

    #port = 995
    #ssl = yes

  }

Change the above to:

inet_listener pop3s {

    port = 995
    ssl = yes

  }

Step 12: Setting up Dovecot LMTP service

On the same file, we need to enable the LMTP service.

Find the entries below:

service lmtp {

unix_listener lmtp {

#mode = 0666

}

And change them to:

service lmtp {

unix_listener /var/spool/postfix/private/dovecot-lmtp {

mode = 0600
user = postfix
group = postfix

 }

Don’t close the file yet.

Step 13: Configuring Dovecot Authentication Socket

We need to configure the authentication socket. So, locate:

service  auth {

...

  # Postfix smtp-auth

  #unix_listener /var/spool/postfix/private/auth {

  #  mode = 0666

  #}



}

And change the above entries to:

service auth {

...

#Postfix smtp-auth

unix_listener /var/spool/postfix/private/auth {

mode = 0666

user=postfix

group=postfix

}

...

Save and close the file when done.

Step 14: Setting Up Dovecot Authentication Process

Next, we will set up Dovecot authentication process by editing the /etc/dovecot/conf.d/10-auth.conf file:

$ sudo nano /etc/dovecot/conf.d/10-auth.conf

Find the entry below.

# disable_plaintext_auth = yes

Then, uncomment it by removing the leading pound symbol

disable_plaintext_auth = yes

Also, we have to change the authentication mechanism from plain to plain login.

On the same file, find the below entry.

auth_mechanisms = plain

And change it to:

auth_mechanisms = plain login

We can now set up the users and passwords configurations.

We will use a password file since it is a flexible method for configuring new users.

First,  disable the default Dovecot behavior for authenticating users using system information.

Locate the line:

!include auth-system.conf.ext

And comment it by adding a pound symbol(#) at the beginning :

#!include auth-system.conf.ext

Then, enable password file configuration. Locate the entry below.

#!include auth-passwdfile.conf.ext

Then, change it to:

!include auth-passwdfile.conf.ext

Save and close the file

Next we will edit the /etc/dovecot/conf.d/auth-passwdfile.conf.ext file.

$ sudo nano /etc/dovecot/conf.d/auth-passwdfile.conf.ext

Make sure the file looks as shown below:

passdb {

  driver = passwd-file

  args = scheme=PLAIN username_format=%u /etc/dovecot/dovecot-users

}



userdb {

driver = static

args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n



 # Default fields that can be overridden by passwd-file

 #default_fields = quota_rule=*:storage=1G

 # Override fields from passwd-file

 #override_fields = home=/home/virtual/%u

}

Save and close the file.

Step 15: Creating Dovecot Password File

The next step is creating a password file for each user that we intend to assign an email account.

$ sudo nano /etc/dovecot/dovecot-users

Users must be added using the format user@domainname.com  followed by the password.

Example:

admin@example.com:{plain}Mis25sOpdsio

You can add as many users as you want and finally save and close the file.

In order for Dovecot to work with SSL for security reasons, we will make a few changes to the /etc/dovecot/conf.d/10-ssl.conf file

$ sudo nano /etc/dovecot/conf.d/10-ssl.conf

Change the ssl parameter value from no to required.

Locate:

ssl = no

And change it to:

ssl = required

Step 16: Configuring Dovecot to Use Let’s Encrypt Certificate

The next step is to point the Let’s encrypt certificate files that were generated earlier to Dovecot.

Find the below two lines on the /etc/dovecot/conf.d/10-ssl.conf file:

#ssl_cert = </etc/dovecot/dovecot.pem

#ssl_key = </etc/dovecot/private/dovecot.pem

Then change their values to:

ssl_cert = </etc/letsencrypt/live/example.com/fullchain.pem

ssl_key = </etc/letsencrypt/live/example.com/privkey.pem

Save and close the file and restart Apache, Postfix and Dovecot for the changes to be effected:

$ sudo service apache2 restart 
$ sudo service postfix restart 
$ sudo service dovecot restart

Step 17: Installing Roundcube

The next step is installing Roundcube email client on Ubuntu 18.04 server.

Since the Roundcube package is available on the Ubuntu software repository, we are going to run the command below to install it:

$ sudo apt-get install roundcube

Press Y and hit Enter when prompted to confirm the installation.

Next, add Roundcube path to the default SSL configuration file:

$ sudo nano /etc/apache2/sites-enabled/000-default-le-ssl.conf

Add Alias /mail /usr/share/roundcube below ServerAlias www.example.com

Alias /mail /usr/share/roundcube

Save and close the file. Then, restart Apache for the changes to take effect

$ sudo service apache2 restart

Step 18: Testing the Configuration

To test the configuration, visit www.example.com/mail on your server and replace example.com with your domain name.

You should see a page similar to the one shown below.

Enter the username and password that you created on the Dovecot password file to login. On the server field, enter ‘localhost’.

If you have reached this step, congratulations! From this point forward, you can start sending and receiving emails right from the Roudcube dashboard as shown below.

To check Postfix error log file, run the command below.

$ sudo tail -f /var/log/syslog | grep postfix

You can also telnet Gmail servers to make sure outbound traffic from port 25 is allowed from your VPS provider.

$ telnet alt4.gmail-smtp-in.l.google.com 25

In case the port is blocked, contact your VPS provider and ask them to enable it.

They will be more than happy to assist you provided you won’t send SPAM emails from the server.

Conclusion

In this guide, we have shown you how to configure an email server with Postfix, Dovecot, and Roundcube on Ubuntu 18.04 VPS.

We hope you enjoyed the guide. To test out configuring email with Postfix, Dovecot, and Roundcube, Sign up with Digital Ocean today and enjoy up to $100 worth of free cloud credit!

How to Set Up Nginx Server Blocks on Ubuntu 18.04 Server

Nginx is one of the best free web servers that offer accelerated content and application delivery. The open-source software was built for speed, improved security, and stability for the world’s busiest sites.

Ubuntu 18.04, on the other hand, is a strong and secure open-source operating system that is fully customizable.

With Nginx and Ubuntu 18.04 combined, one can run a very powerful web server. The beauty of Nginx is the ability to host multiple sites on a single Ubuntu 18.04 server (e.g. a VPS machine).

In this guide, we will show you how to set up multiple websites on Ubuntu 18.04 server with Nginx server blocks.

Prerequisites

In order to accomplish the setup, make sure you have the following:

  1. A VPS account. Signup with Digital Ocean and enjoy up to $100 worth of free trial credit.
  2. A VPS instance running Ubuntu 18.04 as the operating system.
  3. A non-root user that can perform sudo tasks on the VPS instance

Step 1: Installing Nginx Web Server on Ubuntu 18.04

The first step is installing the Nginx web server. Before you do this, SSH to your server and update the software information index to ensure we are pulling the latest version from Ubuntu’s software repository.

$ sudo apt-get update

Then, install Nginx.

$ sudo apt-get install nginx

Output:

Reading package lists... Done

Building dependency tree

Reading state information... Done

The following additional packages will be installed:

  fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libjbig0

  libjpeg-turbo8 libjpeg8 libnginx-mod-http-geoip

  libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter

  libnginx-mod-mail libnginx-mod-stream libtiff5 libwebp6 libxpm4 nginx-common

  nginx-core

Suggested packages:

  libgd-tools fcgiwrap nginx-doc ssl-cert

The following NEW packages will be installed:

  fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libjbig0

  libjpeg-turbo8 libjpeg8 libnginx-mod-http-geoip

  libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter

  libnginx-mod-mail libnginx-mod-stream libtiff5 libwebp6 libxpm4 nginx

  nginx-common nginx-core

0 upgraded, 18 newly installed, 0 to remove and 103 not upgraded.

Need to get 2,423 kB of archives.

After this operation, 7,860 kB of additional disk space will be used.

Do you want to continue? [Y/n]

Press Y when prompted to confirm the installing and hit Enter to continue.

Once Nginx is installed, you can verify the installation by entering the public IP address associated with your VPS machine on a web browser like Google Chrome.

192.0.0.1

You should see the default Nginx web page on Ubuntu 18.04 server as shown below.

Step 2: Creating root Directories for the Websites

By default, Nginx creates one server block with /var/www/html as the root directory. Since we want to host multiple sites on the server, we will have to create a separate directory for each website.

We will be creating directories for example.com and example.net website inside the /var/www/ directory. It is a good practice to create a public_html sub-directory on each website.

To do this, run the commands below:

$ sudo mkdir -p /var/www/example.com/public_html
$ sudo mkdir -p /var/www/example.net/public_html

Remember to create all directories for your websites in this step, the number of websites does not matter provided your server resources can handle the traffic. 

Step 3: Setting the Appropriate File Permissions

If you create directories with the sudo command, they will belong to the root user. However, we want to make sure that the regular users on the Linux system can upload website files.

To do this, we will change the ownership of the website document root directories to the current user.

$ sudo chown -R $USER:$USER /var/www/example.com/public_html
$ sudo chown -R $USER:$USER /var/www/example.net/public_html

To ensure that Nginx will be able to read and execute the files placed on the public_html directories, we need to issue the right permissions.

$ sudo chmod -R 755 /var/www/example.com/public_html
$ sudo chmod -R 755 /var/www/example.net/public_html

Step 4: Creating Sample Nginx Index Files

With the directory setup and permissions in place, we can now go ahead and create a sample index file for each of our website.

We will do this using nano text editor

$ sudo nano /var/www/example.com/index.html

Paste the information below

<html>

<head>

  <title>

  Server Block 1/ Virtual Host 1

  </title>

  </head>

  <body>

  <p>This is Nginx virtual host for example.com website</p>

  </body>

</html>

Then press CTRL+X, Y and Enter to save the file.

Repeat the same procedure for the example.net website.

$ sudo nano /var/www/example.net/index.html

Then, enter the information below on the file.

<html>

 <head>

 <title>

 Server Block 1/ Virtual Host 2

 </title>

 </head>

 <body>

 <p>This is Nginx virtual host for example.net website</p>
 
 </body>

</html>

Save and close the file

Step 5: Creating Nginx Server Blocks on Ubuntu 18.04 for Multiple Websites

Our index pages are ready to be served. However, we haven’t instructed Nginx about the website directories that we have created and the name of our domains. This is where Nginx server blocks or virtual hosts come in to play.

As mentioned a while ago Nginx comes with a default virtual host or server block that serves content from the /var/www. The configuration file of this website is located at /etc/nginx/sites-available/default.

Basically, you need to add an Nginx server block on the /etc/nginx/sites-available/ directory for each website you intend to host with Nginx. However, this configuration file won’t be loaded when Nginx start until a link is created under the /etc/nginx/sites-enabled/ directory.

So to allow Nginx to load our example.com and example.net websites, we need to create a separate configuration file for each website on the /etc/nginx/sites-available/ directory and then create symbolic link on the /etc/nginx/sites-enabled/ directory.

First, create a server block for the example.com website.

$ sudo nano /etc/nginx/sites-available/example.com

Then, enter the information below in the file.

server {

            listen 80;

            listen [::]:80;

            server_name example.com;

            root /var/www/example.com/public_html;

            index index.html;

 

            location / {

                        try_files $uri $uri/ =404;

            }

}

Save and close the file by pressing CTRL+X, Y, and Enter.

We also need to create a new server block for the example.net website

$ sudo nano /etc/nginx/sites-available/example.net

Then, enter the information below in the file.

server {

            listen 80;

            listen [::]:80;

            server_name example.net;

            root /var/www/example.net/public_html;

            index index.html;

 

            location / {

                        try_files $uri $uri/ =404;

            }

}

Save the file by pressing CTRL+X, Y and Enter.

Step 6: Enabling Nginx Server Blocks on Ubuntu 18.04

With the Nginx server blocks in place, we can enable them by running the commands below

$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
$ sudo ln -s /etc/nginx/sites-available/example.net /etc/nginx/sites-enabled/

In order for the changes to take effect, restart Nginx web server.

$ sudo systemctl restart nginx

Step 7: Testing Nginx Server Blocks on Ubuntu 18.04

Once everything is in place, you can test your configuration. If you are running Windows on your local machine, you need to add example.com and example.net together with the public IP address associated with your VPS on the hosts’ file.

C:\Windows\System32\drivers\etc\hosts

Open the file and add the below information. Remember to replace the 192.0.0.1 with your VPS public IP address

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
...

192.0.0.1      example.com
192.0.0.1      example.net

Save the file and visit example.com website. If you followed the guide, you should see the below website.

Then, visit example.net website and confirm if you can see the below output.

Congratulations, if you have reached this far. That’s all when it comes to setting up multiple websites on Nginx with Ubuntu 18.04 server

Conclusion

In this guide, we have taken you through the steps of setting up Nginx server blocks on Ubuntu 18.04 VPS in order to run multiple websites from one server instance.

You can extend the server blocks and hosts as many websites as you want provided your server resources can handle the load.

Signup with Digital Ocean today to enjoy up to $100 worth of free trial credit and run multiple websites on their VPS server.

How to Configure Virtual Hosts On Nginx With CentOS 7

Nginx server blocks also known as Nginx virtual hosts are configurations for setting up multiple websites on a single server.

If you have more than one domain but you don’t want to incur additional costs on VPS plans, you may utilize the Nginx server blocks feature.

Although Nginx is a free and an open-source web server, it can handle more concurrent connections than Apache.

in this guide, we will show you how to set up multiple websites on Nginx with CentOs 7 as the operating system.

Prerequisites

Before you begin, make sure you have the following:

Step 1: Installing Nginx on CentOs 7 Server

We will start off by installing Nginx web server. The package is available on the EPEL repository. So, we need to add the information on the server:

$ sudo yum install epel-release

Then, install Nginx:

$ sudo yum install nginx

Press Y and hit Enter when prompted to confirm the installation.

Once the Nginx web server is installed, start it by typing the command below:

$ sudo systemctl start nginx

Then, enable Nginx to start at boot.

$ sudo systemctl enable nginx

Then, allow the HTTP and HTTPS traffic from CentOs firewall.

$ sudo firewall-cmd --zone=public --permanent --add-service=http
$ sudo firewall-cmd --zone=public --permanent --add-service=https
$ sudo firewall-cmd --reload

You can then confirm if the installation was successful by entering the IP address associated with your server on a browser like Google Chrome.

http://192.0.0.1

You should see the default Nginx home page as shown below:

Step 2: Setting Up Nginx Virtual Host on the First Domain

Next, we are going to configure the first virtual host on Nginx. We will use the example.com as the first domain.

The default Nginx configuration file can be located at /etc/nginx/nginx.conf

Also, the root of the default Nginx website points to  /usr/share/nginx/html.

Since the above directory setup can be a little bit confusing for hosting multiple websites on Nginx, we will create a structure which is more understandable.

First, let’s create the directory to hold our example.com websites data.

$ sudo mkdir -p  /var/www/example.com/public_html

The -p option tells Linux to create any parent directory on the way.

The directory we created above is owned by the root user. However, we want our regular user to be able to modify files on it, so let’s change the directory ownership.

$ sudo chown -R $USER:$USER /var/www/example.com/public_html

Next, we need to set up the appropriate file permissions to allow Nginx to read and execute the files from the public_html directory.

$ sudo chmod -R 755 /var/www/example.com/public_html

Once the directory structure is in place we can create a sample web page on the root of the example.com directory

$ sudo nano /var/www/example.com/public_html/index.html

Then, paste the information below on the file

<html>
  <head>
    <title>Sample web page on example.com website</title>
  </head>
  <body>
    <h1>Nginx server block 1</h1>
    This sample web page confirms that the first Nginx virtual host 
   or server block is working for example.com
  </body>
</html>

Save and close the file by pressing CTRL+X, Y, and Enter

Next, we need to create a server block for the example.com website.

All Nginx virtual host files must end with .conf

The server block configuration files must be placed in the /etc/nginx/conf.d directory.

So let’s create the first Nginx block for the example.com website using nano text editor.

$ sudo nano /etc/nginx/conf.d/example.com.conf

Then, enter the information below on the file

server {
    listen  80;
    server_name example.com;

    location / {
        root  /var/www/example.com/public_html;
        index  index.html index.htm;
    }

    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
        root  /usr/share/nginx/html;
    }
}

Step 3: Setting Up Nginx Virtual Host on the Second Domain

Our server block for the first host is set up. Next, we can go ahead and configure the second virtual host for example.net domain.

First, we create the directory structure.

$ sudo mkdir -p /var/www/example.net/public_html

Then, change the directory ownership.

$ sudo chown -R $USER:$USER /var/www/example.net/public_html

Next, let’s create a sample web page on the example.net root directory.

$ sudo nano /var/www/example.net/public_html/index.html

We can now add the information below to render the HTML web page

<html>
  <head>
    <title>Sample web page on example.net website</title>
  </head>
  <body>
    <h1>Nginx server block 2</h1>
    This sample web page confirms that the first Nginx virtual host 
   or server block is working for example.net
  </body>
</html>

Save and close the file.

We can now go ahead and create a server block for the example.net website.

$ sudo nano /etc/nginx/conf.d/example.net.conf

Then, enter the information below on the file

server {
    listen  80;
    server_name example.net;

    location / {
        root  /var/www/example.net/public_html;
        index  index.html index.htm;
    }

    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
        root  /usr/share/nginx/html;
    }
}

Restart the Nginx web server for the configurations to take effect:

$ sudo systemctl restart nginx

Step 4: Testing Nginx Server Blocks Configuration

To test the configuration add example.com and example.net on your hosts file together with the associated IP address of your VPS machine.

If you are on Windows, locate the file from C:\Windows\System32\drivers\etc\hosts

Then, add the two virtual hosts information at the end as show below.

# Copyright (c) 1993-2009 Microsoft Corp.
...
#	127.0.0.1       localhost
#	::1             localhost

..

149.28.188.94      example.com
149.28.188.94      example.net

Then, example.com on a web browser. You should see a page similar to the one shown below.

You can also visit example.net website which should render the below web page.

If you have reached this far, congratulations! You just learnt how to host multiple websites on Nginx web server running on Centos 7 operating system.

Conclusion

In this guide, we have shown you how to configure multiple websites on CentOs 7 with Nginx using server blocks or virtual hosts.

Sign up with Digital Ocean today and get $100 to host as many websites as you want on one VPS machine.

How to Setup Linux, Nginx, MariaDB and PHP (LEMP) Stack on CentOS 7

LEMP stack is a collection of four open-source applications that are installed together on a server to run dynamic websites. These include Linux, Nginx, MariaDB, and PHP.

When setting up a VPS (Virtual Private Server) account, you will be prompted to select a Linux image (e.g. CentOS 7) when deploying the server. Linux is an operating system based on the Linux Kernel. It is very powerful, secure and runs most of the world’s servers.

Nginx is an event-driven web server popularly used for serving dynamic content. It has a very predictable performance, especially for high trafficked websites.

MariaDB is a fork of MySQL database and is compatible with all SQL commands. It is considered as a drop-in replacement for MySQL. The Relational Database Management System is fast, highly scalable and secure.

PHP is a scripting language that is popularly used as the middleware between the database server and web server.

In this guide, we will show you how to install Nginx, MariaDB, and PHP on a VPS plan running CentOS 7 as the operating system.

Prerequisites

Before you begin make sure you have the following:

Step 1: Installing Nginx on CentOS 7

Nginx packages are available in the EPEL repositories. If you don’t have EPEL repository already installed you can do it by typing:

Nginx packages can be pulled from the EPEL repositories, so you can first install it by typing the command below:

$ sudo yum install epel-release

Once installed, run the command below to install Nginx

$ sudo yum install nginx

Press Y and hit Enter when prompted to confirm the installation. Next, enable the Nginx server by typing the command below:

$ sudo systemctl start nginx

In order to start the web server when the system is rebooted, run the command below:

$ sudo systemctl enable nginx

The default CentOS 7 inbuilt firewall is set to block Nginx traffic. In order to allow inbound traffic to the Nginx server, run the commands below:

$ sudo firewall-cmd --zone=public --permanent --add-service=http
$ sudo firewall-cmd --zone=public --permanent --add-service=https
$ sudo firewall-cmd --reload

To check if Nginx was successfully installed on your server, enter the IP address associated with your VPS instance on a web browser like Google Chrome:

$ 192.0.0.1

You should see the default Nginx home page as shown below:

Alternatively, if you wish to check the status of the web server on the command line tool, enter the command below:

$ sudo systemctl status nginx

Output:

nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset                                             : disabled)

Active: active (running) since Wed 2019-02-13 07:52:14 UTC; 3min 17s ago

Main PID: 12740 (nginx)

CGroup: /system.slice/nginx.service

├─12740 nginx: master process /usr/sbin/nginx

└─12741 nginx: worker process



Feb 13 07:52:14 lemp-server-1 systemd[1]: Starting The nginx HTTP and revers....

Feb 13 07:52:14 lemp-server-1 nginx[12735]: nginx: the configuration file /e...k

Feb 13 07:52:14 lemp-server-1 nginx[12735]: nginx: configuration file /etc/n...l

Feb 13 07:52:14 lemp-server-1 systemd[1]: Failed to read PID from file /run/...t

Feb 13 07:52:14 lemp-server-1 systemd[1]: Started The nginx HTTP and reverse....

Hint: Some lines were ellipsized, use -l to show in full.

Step 2: Installing MariaDB on CentOS 7

Next, we are going to install the MariaDB database server on the CentOS 7 machine. We are going to use the yum package manager

$ sudo yum install mariadb-server

Press Y and hit Enter when prompted to confirm the installation. After a while, your MariaDB server installation should be completed.

To start the database server, run the command below:

$ sudo systemctl start mariadb

Just like we did for the Nginx server, we want to make sure that the database server is started when the system boots. To do this, run the command below

$ sudo systemctl enable mariadb

You can check if the MariaDB server is running by typing the command below

$ sudo systemctl status mariadb

Output:

mariadb.service - MariaDB database server

Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)

Active: active (running) since Wed 2019-02-13 08:02:03 UTC; 56s ago

Main PID: 12913 (mysqld_safe)

CGroup: /system.slice/mariadb.service

├─12913 /bin/sh /usr/bin/mysqld_safe --basedir=/usr

└─13075 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-...



Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: MySQL manual for more instructions.

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: Please report any problems at http://mariadb.org/jira

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: The latest information about MariaDB is available at http...rg/.

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: You can find additional information about the MySQL part at:

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: http://dev.mysql.com

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: Consider joining MariaDB's strong and vibrant community:

Feb 13 08:02:01 lemp-server-1 mariadb-prepare-db-dir[12835]: https://mariadb.org/get-involved/

Feb 13 08:02:01 lemp-server-1 mysqld_safe[12913]: 190213 08:02:01 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.

Feb 13 08:02:01 lemp-server-1 mysqld_safe[12913]: 190213 08:02:01 mysqld_safe Starting mysqld daemon with databases f...mysql

Feb 13 08:02:03 lemp-server-1 systemd[1]: Started MariaDB database server.

The default MariaDB installation is not secure, so we are going to run the command below to set a root password, remove anonymous users and disable remote access

The default MariaDB installation is not secure, so we are going to run the command below to set a root password, remove anonymous users and disable remote access

$ sudo mysql_secure_installation
Enter current password for root (enter for none):
Set root password: Y
New password: STRONGPASSWORDHERE
Re-enter new password: REPEATSTRONGPASSWORDHERE
Remove anonymous users? [Y/n] Y
Disallow root login remotely? [Y/n]: Y
Remove test database and access to it? [Y/n]: Y
Reload privilege tables now? [Y/n]: Y

Output:

Cleaning up...
All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!

Once the MariaDB  installation is complete, you can log in to the database server using the command below:

$ sudo mysql -uroot -p

Enter the root password of your MariaDB server and press Enter to continue.

You should see the MariaDB command line interface

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 12
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Once logged in, you can run any SQL command e.g., to list databases, run the command below:

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Step 3: Installing PHP on CentOS 7

Next, we are going to install PHP(Hypertext Preprocessor).

This is a general-purpose scripting language that is highly suitable for web applications. In fact, most Content Management Systems (CMS) are coded in PHP.

To install the PHP software package, run the command below:

$ sudo yum install php php-mysql php-fpm

Again, press Y and hit Enter when prompted to confirm the PHP installation on CentOS 7 server.

Once PHP is installed, we will make a few changes to the configuration file. Open the file using nano text editor

$ sudo nano /etc/php.ini

Then, look for the line below:

;cgi.fix_pathinfo=1

And change it to:

cgi.fix_pathinfo=0

Press CTRL+X, Y and hit Enter to continue.

Then, we are going to edit the PHP-fpm configuration file:

$ sudo nano /etc/php-fpm.d/www.conf

Make the following changes to the file:

listen = /var/run/php-fpm/php-fpm.sock
listen.owner = nginx
listen.group = nginx
user = nginx
group = nginx

We can now start the PHP package by running the command below:

$ sudo systemctl start php-fpm
$ sudo systemctl enable php-fpm

To enable Nginx to process PHP pages, we are going to create a configuration file using nano text editor

$ sudo nano /etc/nginx/conf.d/default.conf

Then, enter the following details:

server {
    listen   80;
    server_name  192.0.0.1;

    # note that these lines are originally from the "location /" block
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Save the file by pressing CTRL+X, Y, and Enter. Then, restart the Nginx web server:

$ sudo systemctl restart nginx

To test if PHP is working, create PHP info file:

$ sudo nano sudo nano /usr/share/nginx/html/info.php

Then enter the information below:

<?php
 phpinfo();
?>

Save and close the file. Then, on a web browser visit the page below and remember to replace 192.0.0.1 with your IP address:

http://192.0.0.1/info.php

You should see a page similar to the one shown below with lots of information about PHP

Conclusion

That’s all when it comes to installing the LEMP stack on your VPS machine. Once the setup is complete, you can import your website files and have a fully functioning web server.

Remember to point your domain name DNS records the public IP address associated with your VPS machine.

New to VPS hosting and cloud computing. Sign up with Digitial Ocean today and enjoy up to $100 worth of free trial credit.

How to Install MySQL 8.0 Community Edition on Ubuntu 18.04

As of February 2019, MySQL 8.0 was the newest version of MySQL. The new and exciting version has great improvements that you probably don’t want to miss.

Being an open source database, MySQL 8.0 has been re-engineered to offer most Windows SQL  functions as well as extended JSON functions. The InnoDB engine has been improved to offer a crash-safe environment and the performance schema has been enhanced.

Another great feature that ships with MySQL 8.0 is role management for organizing users better.

You can take advantage of all these great MySQL 8.0 features by installing it on your Virtual Private Server(VPS).

This guide takes you through the steps of setting up MySQL 8.0 community edition on your Ubuntu 18.04 server.

Prerequisites

Before you begin, make sure you have the following:

  1. A VPS account. Signup with Digital Ocean and get free $100 credit to test this article and other cloud services.
  2. A non-root user that can perform sudo tasks on your Ubuntu 18.04 server.

Step 1: Downloading MySQL 8.0 Repository

The default MySQL edition available on the Ubuntu software repository is not the newest version. So we are going to manually download the repository using wget command.

First,  cd to the tmp directory:

$ cd /tmp

Then, add the repository.

$ wget https://dev.mysql.com/get/mysql-apt-config_0.8.12-1_all.deb

Next, we are going to use the dpkg command to install the repository on Ubuntu 18.04 server:

$ sudo dpkg -i mysql-apt-config_0.8.12-1_all.deb

A dialog box will appear, choose OK and press Enter to continue.

Step 2: Installing MySQL 8.0 On Ubuntu 18.04 VPS

Next, update the package information index:

$ sudo apt-get update

To install MySQL, run the command below:

$ sudo apt-get install  mysql-server

Press Y and hit Enter when prompted to confirm the installation.

Towards the end of the installation, you will be prompted to enter the root user of your MySQL server; don’t confuse this with the root account of your VPS server.

 

Enter a strong password and hit Enter to continue. You will be prompted to repeat the password.

Select OK on the next dialog box and hit Enter

Then, select the right authentication plugin

The installation should be successfully installed.  You can confirm the MySQL version on your Ubuntu 18.04 server by running the command below:

$ mysql --version

Output:

mysql  Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)

Step 3: Loggin to the MySQL 8.0 Server

To log in to the MySQL 8.0 server, run the command below:

$mysql -uroot -p

Enter the root password of the MySQL server and hit Enter to continue.

You will get a prompt similar to the one shown below:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.15 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

You can then start issuing commands on the MySQL command line interface e.g., show databases;

mysql> show databases;

Output:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec

Conclusion

In this article, we have taken you through the steps of configuring MySQL 8.0 on your Ubuntu 18.04 VPS.

Sign up with Digital Ocean VPS today and get free $100 to deploy MySQL 8.0  on your next project to take advantage of improved features that you can’t find on other versions of MySQL.

How to Set up Multiple Websites on Ubuntu 18.04 VPS with Apache

Apache is one of the best open-source web servers that run millions of sites on the web. It is very fast, secure, flexible, and takes minutes to set up on a Linux server e.g., Ubuntu 18.04.

If you have purchased a VPS plan, there are high chances that you want to run multiple websites on your server. This will reduce additional costs which you would have incurred to deploy additional VPS machines.

Running multiple websites is possible on a single Ubuntu 18.04 server because Apache comes with a feature known as Virtual hosts that allows you to configure unlimited websites on a single server.

In this guide, we will take you through the steps of configuring multiple websites on your Ubuntu 18.04 with Apache.

Prerequisites

To follow along with the guide, you will require the following:

  1. A VPS account. Sign up with Digital Ocean today and get up to $100 worth of free credit to test this article and other cloud products.
  2. A non-root user account that can perform sudo tasks on your VPS server.

For better clarification, we will set up two domains: example.com and example.net on the server.

Step 1: Installing Apache Web Server

The first step is installing the web server. We will use Ubuntu apt manager to install Apache.

First,  update the package information index:

$ sudo apt-get update

Then, install Apache

$ sudo apt-get install apache2

Press Y and hit Enter when prompted to confirm the installation.

Once installed, you can enter the IP address associated with your VPS machine on a web browser like Google Chrome. If the Apache installation was completed successfully, you should see a page similar to the one shown below:

Step 2: Creating the First Virtual Host on Ubuntu 18.04 Server

Apache creates a virtual host when installed for the first time. The configuration file can be located at /etc/apache2/sites-available/000-default.conf. To avoid any conflicts, we need to  disable the virtual host by running the command below.

$ sudo a2dissite 000-default.conf

Next, create a virtual host configuration for the example.com domain.

$ sudo mkdir -p /var/www/example.com/public_html

Next,  we will change the ownership of the directory that we have created above.

$ sudo chown -R $USER:$USER /var/www/example.com/public_html

Then,  issue the right file permissions to the directory.

$ sudo chmod -R 755 /var/www/example.com/public_html

Also, to ensure that newly created files and directories inherit the permissions we  created above, we are going to run the command below:

$ sudo find /var/www/example.com/public_html -type d -exec chmod g+s {} \;

Once we have the directory for the example.com website in place, we can create a new virtual host configuration file and reference to that directory:

$ sudo nano /etc/apache2/sites-available/example.com.conf

Paste the information below:

<VirtualHost *:80>

    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/example.com/public_html>

Options -Indexes +FollowSymLinks -MultiViews
AllowOverride All          
Require all granted

</Directory>

</VirtualHost>

Next, enable the example.com virtual host by running the command below.

$ sudo a2ensite example.com.conf

We can create a sample home page for the example.com website. So, create the file using nano text editor:

$ sudo nano /var/www/example.com/public_html/index.html

Paste the information below in the file.

<html>
  <head>
    <title>Site 1</title>
  </head>
  <body>
    <h1>This is a sample page for example.com website</h1>
  </body>
</html>

Step 3: Creating the Second Virtual Host on Ubuntu 18.04 Server

Just like we have done for the example.com website, we need to create a directory for the example.net virtual host on Apache.

$ sudo mkdir -p /var/www/example.net/public_html

Then we need to change the file ownership and associate them to the currently logged in user.

$ sudo chown -R $USER:$USER /var/www/example.net/public_html

Then, run the command below to issue the right permissions.

$ sudo chmod -R 755 /var/www/example.net/public_html

Make sure that files created under the directory inherit permissions from the parent directory.

$ sudo find /var/www/example.net/public_html -type d -exec chmod g+s {} \;

Create a virtual host file for the example.net website.

$ sudo nano /etc/apache2/sites-available/example.net.conf

Then, paste the information below.

<VirtualHost *:80>
    ServerAdmin admin@example.net
    ServerName example.net
    ServerAlias www.example.net
    DocumentRoot /var/www/example.net/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/example.net/public_html>

Options -Indexes +FollowSymLinks -MultiViews
AllowOverride All           
Require all granted

</Directory>

</VirtualHost>

Close and save the file by pressing CTRL+X, Y and hit Enter.

Next, enable the example.net virtual host by running the command below:

$ sudo a2ensite example.net.conf

Next, create a sample home page for the example.net website.

$ sudo nano /var/www/example.net/public_html/index.html

Enter the information below;

<html>

  <head>

    <title>Site 2</title>

  </head>

  <body>

    <h1>This is a sample page for example.net website</h1>

  </body>

</html>

Press CTRL+X, Y and Enter to save the file.

Step 3: Restart Apache and Test the Configuration

In order for Apache to load the settings for the newly created virtual hosts, it must be restarted.

$ sudo systemctl restart apache2

Then, on your local computer, add the example.com and example.net domain names on the hosts file and point them to the public IP address of your VPS machine and save the file.

If you are running Windows, edit the file c:\Windows\System32\Drivers\etc\hosts and save it. Remember to replace 192.88.99.0 with the IP address associated with your VPS machine:

# Copyright (c) 1993-2009 Microsoft Corp.

...

# localhost name resolution is handled within DNS itself.

#             127.0.0.1       localhost

#             ::1             localhost

192.88.99.1 example.net

192.88.99.1 example.com

..

Then, save the file and visit the example.com on your browser. You should see a page similar to the one below:

Next, visit example.net on your browser to test the 2nd virtual host. Your browser should display the page shown below.

Conclusion

That’s all when it comes to hosting multiple sites on your Ubuntu 16.04 server with Apache. A virtual host is a great feature that you can leverage to reduce cost of ownership when you wish to run multiple sites on a single VPS machine.

Remember, you can configure as many websites as you want provided your VPS plan can handle the disk space, memory, and bandwidth.

The virtual hosts configuration should work pretty well on any Digital Ocean server.  Sign up with Digitial Ocean today and get $100 worth of free trial credit.

Mpesa B2C(Business to Customer) API

Mpesa B2C API is a gateway for disbursing funds to customers through Mpesa Bulk Payment account.

The Safaricom Business to Client API is useful when you want to make payments to Mpesa users from your company’s Mpesa account.

Using the Mpesa Portal for the payments is rather cumbersome and furthermore, you can automate the process of making payments to customers depending on your business logic.

In this guide, we will focus on setting up Mpesa B2C API using PHP.

Prerequisites

  1. An account from Mpesa developer portal
  2. An active bulk payment account from Mpesa(application is free, but you will require your business certificate, PIN of directors, a single leaf of cancelled cheque book and a photo or utility bill to prove existence of your business.)
  3. A domain name (e.g. www.example.com). This will help you create call back URL to notify your system when your transaction is finalized on the Mpesa side.
  4. A hosting plan (Bluehost is recommended)
  5. Knowledge of MySQL database
  6. Knowledge of PHP scripting Language

Step 1: Signing up with Mpesa Developer Portal

First, create an account at Mpesa Developer Portal If you don’t have an account. You will be required to supply your names, email address, Mobile number and other details.

Step 2: Create a B2C App(Business to Customer/Client)

Once your account is ready, sign in on the developer portal and create a B2C API. To do this, click on My APPs at the top Menu. Then click Add a new APP

On the next screen, enter the name of your app and check the box written “MPesa Sandbox For MPesa Sanbox B2B, B2C And C2B APIs”.

Your Mpesa B2C app will be created and approved within seconds and you will get a consumer secret and a consumer key.

Step 3: Making Payments to a Customer

Once you have the consumer key and consumer secret, you can start making requests to the Mpesa B2C end point using the PHP code below:

<?php

$shortcode="YOUR_SHORT_CODE_HERE";
$initiatorname="USER_NAME_FROM_MPESA_PORTAL_HERE";
$initiatorpassword="YOUR_PASSWORD_HERE";


$consumerkey    ="YOUR_CONSUMER_SECRET_HERE";
$consumersecret ="YOUR_CONSUMER_SECRET_HERE";


$commandid='BusinessPayment';
$recipient="25472XXXXXXX";
$amount="100";
$remarks='TEST BUSINESS DISBURSAL';
$occassion='JANUARY 2019';


$QueueTimeOutURL="YOUR_QUEUE_TIMEOUT_URL_HERE";
$ResultURL="YOUR_RESULT_URLHERE";



/*The below are production URLS CHANGE TO SANDBOX IF YOU HAVEN'T GONE LIVE */

$authorizationurl='https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$paymentrequesturl="https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";



/* FIRST WE AUTHENTICATE OUR API CALL */

/* BEGIN AUTHENTICATION TO GET ACCESS TOKEN*/

  // Request headers
  $headers = array(	
    'Content-Type: application/json; charset=utf-8'
  );

  // Request
  $ch = curl_init($authorizationurl);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  //curl_setopt($ch, CURLOPT_HEADER, TRUE); // Includes the header in the output
  curl_setopt($ch, CURLOPT_HEADER, FALSE); // excludes the header in the output

  curl_setopt($ch, CURLOPT_USERPWD, $consumerkey . ":" . $consumersecret); // HTTP Basic Authentication
  $result = curl_exec($ch);	

if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
    exit();
}



$result = json_decode($result);

$access_token=$result->access_token;

curl_close($ch);


/* END AUTHENTICATION */



/* BEGIN PAYMENT REQUEST IF WE GOT ACCESS TOKEN*





if(!$access_token)

{

  echo " Invalid access token ". print_r($result);

}

else


{



$publicKey = "-----BEGIN CERTIFICATE-----
MIIGkzCCBXugAwIBAgIKXfBp5gAAAD+hNjANBgkqhkiG9w0BAQsFADBbMRMwEQYK
CZImiZPyLGQBGRYDbmV0MRkwFwYKCZImiZPyLGQBGRYJc2FmYXJpY29tMSkwJwYD
VQQDEyBTYWZhcmljb20gSW50ZXJuYWwgSXNzdWluZyBDQSAwMjAeFw0xNzA0MjUx
NjA3MjRaFw0xODAzMjExMzIwMTNaMIGNMQswCQYDVQQGEwJLRTEQMA4GA1UECBMH
TmFpcm9iaTEQMA4GA1UEBxMHTmFpcm9iaTEaMBgGA1UEChMRU2FmYXJpY29tIExp
bWl0ZWQxEzARBgNVBAsTClRlY2hub2xvZ3kxKTAnBgNVBAMTIGFwaWdlZS5hcGlj
YWxsZXIuc2FmYXJpY29tLmNvLmtlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAoknIb5Tm1hxOVdFsOejAs6veAai32Zv442BLuOGkFKUeCUM2s0K8XEsU
t6BP25rQGNlTCTEqfdtRrym6bt5k0fTDscf0yMCoYzaxTh1mejg8rPO6bD8MJB0c
FWRUeLEyWjMeEPsYVSJFv7T58IdAn7/RhkrpBl1dT7SmIZfNVkIlD35+Cxgab+u7
+c7dHh6mWguEEoE3NbV7Xjl60zbD/Buvmu6i9EYz+27jNVPI6pRXHvp+ajIzTSsi
eD8Ztz1eoC9mphErasAGpMbR1sba9bM6hjw4tyTWnJDz7RdQQmnsW1NfFdYdK0qD
RKUX7SG6rQkBqVhndFve4SDFRq6wvQIDAQABo4IDJDCCAyAwHQYDVR0OBBYEFG2w
ycrgEBPFzPUZVjh8KoJ3EpuyMB8GA1UdIwQYMBaAFOsy1E9+YJo6mCBjug1evuh5
TtUkMIIBOwYDVR0fBIIBMjCCAS4wggEqoIIBJqCCASKGgdZsZGFwOi8vL0NOPVNh
ZmFyaWNvbSUyMEludGVybmFsJTIwSXNzdWluZyUyMENBJTIwMDIsQ049U1ZEVDNJ
U1NDQTAxLENOPUNEUCxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2
aWNlcyxDTj1Db25maWd1cmF0aW9uLERDPXNhZmFyaWNvbSxEQz1uZXQ/Y2VydGlm
aWNhdGVSZXZvY2F0aW9uTGlzdD9iYXNlP29iamVjdENsYXNzPWNSTERpc3RyaWJ1
dGlvblBvaW50hkdodHRwOi8vY3JsLnNhZmFyaWNvbS5jby5rZS9TYWZhcmljb20l
MjBJbnRlcm5hbCUyMElzc3VpbmclMjBDQSUyMDAyLmNybDCCAQkGCCsGAQUFBwEB
BIH8MIH5MIHJBggrBgEFBQcwAoaBvGxkYXA6Ly8vQ049U2FmYXJpY29tJTIwSW50
ZXJuYWwlMjBJc3N1aW5nJTIwQ0ElMjAwMixDTj1BSUEsQ049UHVibGljJTIwS2V5
JTIwU2VydmljZXMsQ049U2VydmljZXMsQ049Q29uZmlndXJhdGlvbixEQz1zYWZh
cmljb20sREM9bmV0P2NBQ2VydGlmaWNhdGU/YmFzZT9vYmplY3RDbGFzcz1jZXJ0
aWZpY2F0aW9uQXV0aG9yaXR5MCsGCCsGAQUFBzABhh9odHRwOi8vY3JsLnNhZmFy
aWNvbS5jby5rZS9vY3NwMAsGA1UdDwQEAwIFoDA9BgkrBgEEAYI3FQcEMDAuBiYr
BgEEAYI3FQiHz4xWhMLEA4XphTaE3tENhqCICGeGwcdsg7m5awIBZAIBDDAdBgNV
HSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwJwYJKwYBBAGCNxUKBBowGDAKBggr
BgEFBQcDAjAKBggrBgEFBQcDATANBgkqhkiG9w0BAQsFAAOCAQEAC/hWx7KTwSYr
x2SOyyHNLTRmCnCJmqxA/Q+IzpW1mGtw4Sb/8jdsoWrDiYLxoKGkgkvmQmB2J3zU
ngzJIM2EeU921vbjLqX9sLWStZbNC2Udk5HEecdpe1AN/ltIoE09ntglUNINyCmf
zChs2maF0Rd/y5hGnMM9bX9ub0sqrkzL3ihfmv4vkXNxYR8k246ZZ8tjQEVsKehE
dqAmj8WYkYdWIHQlkKFP9ba0RJv7aBKb8/KP+qZ5hJip0I5Ey6JJ3wlEWRWUYUKh
gYoPHrJ92ToadnFCCpOlLKWc0xVxANofy6fqreOVboPO0qTAYpoXakmgeRNLUiar
0ah6M/q/KA==
-----END CERTIFICATE-----
";


openssl_public_encrypt($initiatorpassword, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);

//GENERATE SECURITY CREDENTIAL USING THE PUBLIC KEY ABOVE

$securitycredential=base64_encode($encrypted);

/* MAKE PAYMENT REQUEST */


$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $paymentrequesturl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$access_token)); 

$curl_post_data = array(  
 
  'InitiatorName' => $initiatorname,
  'SecurityCredential' => $securitycredential,
  'CommandID' =>  $commandid,
  'Amount' =>  $amount,
  'PartyA' => $shortcode,
  'PartyB' =>  $recipient,  
  'Remarks' => $remarks,
  'QueueTimeOutURL' => $QueueTimeOutURL,
  'ResultURL' => $ResultURL,
  'Occassion' => $occassion
);

$data_string = json_encode($curl_post_data);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);


  $response = json_decode($curl_response);

  if(!isset($response->ConversationID))

  {
  echo "There was an error when submitting your request: $response->errorMessage";
  
  }

  else

  {
  echo "Success, $response->ResponseDescription ";
  }


}


?>

Step 4: Queue Timeout and Result URLs

The Mpesa B2C API Queue timeout URL is called if the transactions times out from the Mpesa side. Result URL is called once the transaction is finalized.

When you receive the status of the transaction on the results URL, you should analyze the response to see if the transaction succeeded or not.

A transaction may fail due to the following reasons:

  1. Incorrect security credentials
  2. Insufficient funds from the Mpesa B2C account. Please note the minimum amount you can load on the B2C account is Kshs. 5,000/=. But you should not worry, if you are just testing out the  Mpesa Business to Customer API, you can load the amount and then send it back to your phone number
  3. Authorization error: This happens if the username that you have specified does not have the rights to initiate the Mpesa B2C transaction.

Sample Success Response from Mpesa B2C gateway

{  
   "Result":{  
      "ResultType":0,
      "ResultCode":0,
      "ResultDesc":"The service request is processed successfully.",
      "OriginatorConversationID":"11369-5305957-1",
      "ConversationID":"AG_20190103_00004ad7c21029e28510",
      "TransactionID":"NA30XPKKVCW",
      "ResultParameters":{  
         "ResultParameter":[  
            {  
               "Key":"TransactionAmount",
               "Value":100
            },
            {  
               "Key":"TransactionReceipt",
               "Value":"NA30XKHVCW"
            },
            {  
               "Key":"ReceiverPartyPublicName",
               "Value":"2547XXXXXXX - JOHN DOE"
            },
            {  
               "Key":"TransactionCompletedDateTime",
               "Value":"03.01.2019 17:48:32"
            },
            {  
               "Key":"B2CUtilityAccountAvailableFunds",
               "Value":4425.00
            },
            {  
               "Key":"B2CWorkingAccountAvailableFunds",
               "Value":0.00
            },
            {  
               "Key":"B2CRecipientIsRegisteredCustomer",
               "Value":"Y"
            },
            {  
               "Key":"B2CChargesPaidAccountAvailableFunds",
               "Value":0.00
            }
         ]
      },
      "ReferenceData":{  
         "ReferenceItem":{  
            "Key":"QueueTimeoutURL",
            "Value":"http:\/\/internalapi.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"
         }
      }
   }
}

Sample Error Message from Mpesa B2C API Gateway- The Initiator Information is Invalid

{  
   "Result":{  
      "ResultType":0,
      "ResultCode":2001,
      "ResultDesc":"The initiator information is invalid.",
      "OriginatorConversationID":"7488-6256766-1",
      "ConversationID":"AG_20190104_00004ce9fc41b15aa227",
      "TransactionID":"NA43XZPDE3",
      "ReferenceData":{  
         "ReferenceItem":{  
            "Key":"QueueTimeoutURL",
            "Value":"http:\/\/internalapi.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"
         }
      }
   }
}

Sample Safaricom Mpesa B2C API Insufficient Funds JSON Error

{  
   "Result":{  
      "ResultType":0,
      "ResultCode":1,
      "ResultDesc":"The balance is insufficient for the transaction.",
      "OriginatorConversationID":"18221-6293510-1",
      "ConversationID":"AG_20190104_00005b7d5130c96080a9",
      "TransactionID":"Ni417ZUTBX",
      "ReferenceData":{  
         "ReferenceItem":{  
            "Key":"QueueTimeoutURL",
            "Value":"http:\/\/internalapi.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"
         }
      }
   }
}

In simple terms, if the ResultCode parameter is 0, then it means the transaction is completed and successful. Any other values means an error.

Conclusion

This guide should give you an overview of how you should develop a Safaricom Mpesa B2C API. While it is not a conclusive list of all the things that you might require, it will assist you to program your app.

Use the code given here at your own risk. Also, never save your Mpesa login portal password on your hosting files for security reasons.

How to Setup Fault-Tolerant Database with MySQL Group Replication on Ubuntu 18.04

MySQL group replication is a plugin that provides the functionality of creating a shared-nothing fault-tolerant database architecture. The add-on utilizes a group of servers that interact with each other to agree on the state of a database at any given time and any changes that may occur.

The plugin is useful when creating mission critical applications that require  highly available databases. It simply creates an additional layer of security by coordinating redundant servers in a simple way.

Data is replicated across multiple servers and if a member leaves a group, an auto-detect mechanisms notifies the other members about the change.  If the remaining servers can agree on a quorum, database operations resume as expected.

In this guide, we will walk you through the steps of setting up MySQL Group Replication plugin on Ubuntu 18.04 server.

Prerequisite

Step 1: Installing MySQL Community Edition

The default MySQL package available on the Ubuntu software repository does not support MySQL Group Replication plugin. So we will manually pull deb packages from the official MySQL download page and install the Community Edition.

We will repeat this procedure in all the 3 servers since each server will house its own copy of the replicated MySQL database:

SSH to server1 and navigate to the tmp directory using Linux cd command:

$ cd /tmp

Then, use wget command to download a tar archive with all the deb package files that we are going to install:

$ wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-server_5.7.23-1ubuntu18.04_amd64.deb-bundle.tar

Once the file is downloaded, make an installation directory:

$ mkdir installation

Unzip the archive file to the installation directory that we created:

$ tar -xvf mysql-server_5.7.23-1ubuntu18.04_amd64.deb-bundle.tar -C installation/

All the necessary deb files should now be placed under the installation directory. However, before we install them, we need to install libaio1 and libmecab2 dependencies for MySQL to work.

So,first update the package information index, then install the dependencies using the commands below:

$ sudo apt-get update
$ sudo apt-get install libaio1
$ sudo apt-get install libmecab2

Next, cd  to the installation directory:

$ cd installation

Then, install MySQL community server using the dpkg package manager by running the below commands one by one:

$ sudo dpkg -i mysql-common_5.7.23-1ubuntu18.04_amd64.deb
$ sudo dpkg -i mysql-community-client_5.7.23-1ubuntu18.04_amd64.deb
$ sudo dpkg -i mysql-client_5.7.23-1ubuntu18.04_amd64.deb
$ sudo dpkg -i mysql-community-server_5.7.23-1ubuntu18.04_amd64.deb

Enter a secure root password for your MySQL server when prompted.Repeat this procedure in all the 3 servers participating in the group replication.

Step 2: Generating a Universally Unique Identifier (UUID) for the Group

Next, we will generate Universally Unique Identifier (UUID) for our group. To do this, login to MySQL on server1 using the command below:

$ sudo mysql -uroot -p

Enter the root password of MySQL server that your created above  when prompted and press Enter to continue.

Then, run the below SQL command to generate the UUID:

SELECT UUID();
+————————————–+
| UUID()                               |
+————————————–+
| 99bfc355-cd41-11e8-ba46-5600018c8695 |
+————————————–+

Copy the value generated above, we will need it when making changes to the MySQL server configuration file.

Step 3: Configuring MySQL Group Replication Settings on server1

Next, we are going to configure server1 to support group replication by editing the MySQL configuration file using nano editor:

$ sudo nano /etc/mysql/my.cnf

Then, paste the below content at  the end of the file:

[mysqld]

bind-address= 0.0.0.0
server_id=1
gtid_mode=ON
enforce_gtid_consistency=ON
binlog_checksum=NONE

The above configurations enable remote access to the MySQL server and assigns 1 as the unique server identifier. They also instruct MySQL  to enable global transaction identifiers and disable checksum for the binary log file.

Next, paste the settings below:

log_bin=binlog
log_slave_updates=ON
binlog_format=ROW
master_info_repository=TABLE
relay_log_info_repository=TABLE

These configurations enable binary logging in a row-based format and instruct MySQL to store replication information in system tables instead of files to speed up replication.

Finally, paste the below group replication information and remember to replace the group name with the UUID that we generated earlier.

The address 192.0.2.1 should match the private IP address of your virtual machine instances.

transaction_write_set_extraction=XXHASH64
loose-group_replication_group_name=”99bfc355-cd41-11e8-ba46-5600018c8695″
loose-group_replication_start_on_boot=off
loose-group_replication_local_address= “192.0.2.1:33061”
loose-group_replication_group_seeds= “192.0.2.1:33061, 192.0.2.2:33061, 192.0.2.3:33061”
loose-group_replication_bootstrap_group=offreport_host=192.0.2.1

The loose-group_replication_local_address should match the private IP address of  server1.

Also, make sure to include all the 3 private IP addresses for the servers participating in group replication as the value of the loose-group_replication_group_seeds.  

For the sake of simplicity, we have used the IP addresses 192.0.2.1, 192.0.2.2 and 192.0.2.3 for server1, server2 and server3 respectively.

Remember, the recommended port for MySQL Group Replication is 33061.

The loose- prefix  prevents MySQL server to encounter problems if the server starts before the plugin is installed.

The transaction_write_set_extraction configures the server to gather the write instructions set and encode it using the XXHASH64 algorithm

The group_replication_group_name sets the name of the group that is being created.

When set to off, the group_replication_start_on_boot directive disables the plugin from loading when the server starts.

The value specified in the group_replication_local_address tells the plugin to use the IP address and port combination to communicate to the other members of the group.

The  group_replication_group_seeds parameter is used to set the hosts and ports that will be used by new members joining the group. Although we have included all the 3 server addresses here, it is not mandatory to do this and you can choose only a few members as the value for the seeds depending on your group size.

We have set the loose-group_replication_bootstrap_group to off to avoid creating a new group with the same name every time our server reboots.

Once you have made the above changes, save the file by pressing CTRL+X, Y and Enter. Then run the command below to restart MySQL service on server1:

$ sudo service mysql restart

Step 4: Setting up User Credentials for the Group Replication Recovery Channel

To achieve distributed recovery, MySQL Group Replication uses the asynchronous replication protocol. This technology synchronizes new members before adding them to the group using group_replication_recovery channel .

Therefore a replication user must be created on each member in the group to aid in transferring transactions. To achieve this, log in to server1 using the command below:

$ sudo mysql -uroot -p

Enter the root password when prompted and hit Enter. Then disable binary logging to avoid logging the changes on the binary file:

mysql> SET SQL_LOG_BIN=0;

Then, run the commands below one by one to create the replication user and assign the correct privileges. Remember to replace PASSWORD with a strong value for security purposes.

mysql> CREATE USER ‘rep_user’@‘%’ IDENTIFIED BY ‘PASSWORD’;
mysql> GRANT REPLICATION SLAVE ON *.* TO ‘rep_user’@‘%’;
mysql> FLUSH PRIVILEGES;
mysql> SET SQL_LOG_BIN=1;

With the user configured, we can use the CHANGE MASTER TO query to tell MySQL  to assign the user to the group_replication_recovery channel:

mysql> CHANGE MASTER TO MASTER_USER=‘rep_user’, MASTER_PASSWORD=‘PASSWORD’      FOR CHANNEL ‘group_replication_recovery’;

Step 5: Installing the Group Replication Plugin and Bootstrapping the Group

We can now go ahead and install the group replication plugin on server1 using the command below:

mysql> INSTALL PLUGIN group_replication SONAME ‘group_replication.so’;

Everything is now set and we can now bootstrap the group with the commands below:

mysql>SET GLOBAL group_replication_bootstrap_group=ON;
mysql>START GROUP_REPLICATION;

To avoid bootstrapping multiple groups with the same name when the server restarts, we will set the GLOBAL group_replication_bootstrap_group back to off :

mysql>SET GLOBAL group_replication_bootstrap_group=OFF;

Once the group is started, we can check its status:

mysql> SELECT MEMBER_ID,MEMBER_HOST,MEMBER_STATE FROM performance_schema.replication_group_members;

Output:

+————————————–+————-+————–+
| MEMBER_ID                            | MEMBER_HOST | MEMBER_STATE |
+————————————–+————-+————–+
| 18cf9650-cde5-11e8-9e26-560001b743c7 | 192.0.2.1   | ONLINE |
+————————————–+————-+————–+

The output above shows that server1 is online and indeed a member of our group.

MySQL Group Replication works with Innodb tables. So , we are going to create a test database to see if the database server is working as expected.

mysql> create database test_replication;

Then, we can switch to the database:

mysql> use test_replication;

Next, we need to create a test_table:

mysql> create table test_table (student_id INT PRIMARY KEY,
student_name VARCHAR(30) NOT NULL) Engine = InnoDB;

We can confirm the presence of the table by running the command below:

mysql> show tables;

Output:

+—————————-+
| Tables_in_test_replication |
+—————————-+
| test_table                 |
+—————————-+

Step 6: Configuring server2

Once server1 is up and our group is running, we can now go ahead and configure server2 and join it to the group.

SSH to server2 and make sure you have installed MySQL Community Edition server as outlined in step 1. Then, edit the MySQL configuration file using a text editor:

$ sudo nano /etc/mysql/my.cnf

Paste the below settings at the end of the file and remember to replace 192.0.2.2 with the correct private addresses of your VPS :

[mysqld]

bind-address= 0.0.0.0
server_id=2
gtid_mode=ON
enforce_gtid_consistency=ON
binlog_checksum=NONE

log_bin=binlog
log_slave_updates=ON
binlog_format=ROW
master_info_repository=TABLE
relay_log_info_repository=TABLE

transaction_write_set_extraction=XXHASH64
loose-group_replication_group_name=”99bfc355-cd41-11e8-ba46-5600018c8695″
loose-group_replication_start_on_boot=off
loose-group_replication_local_address= “192.0.2.2:33061”
loose-group_replication_group_seeds= “192.0.2.1:33061, 192.0.2.2:33061, 192.0.2.3:33061”
loose-group_replication_bootstrap_group=off

report_host=192.0.2.2

Press CTRL+X, Y and Enter to save the file.

Restart MySQL server for the changes to take effect using the command below:

$ sudo service mysql restart

Login to MySQL on server2:

$ sudo mysql-uroot -p

Enter your database password when prompted and hit Enter.

Next, create the replication user for the group replication recovery channel on server2 by running the commands below.

mysql> SET SQL_LOG_BIN=0;
mysql> CREATE USER ‘rep_user’@‘%’ IDENTIFIED BY ‘PASSWORD’;
mysql> GRANT REPLICATION SLAVE ON *.* TO ‘rep_user’@‘%’;
mysql> FLUSH PRIVILEGES;
mysql> SET SQL_LOG_BIN=1;
mysql> CHANGE MASTER TO MASTER_USER=‘rep_user’, MASTER_PASSWORD=‘PASSWORD’      FOR CHANNEL ‘group_replication_recovery’;

Then, install the MySQL group replication plugin on server2 using the commands below:

mysql>INSTALL PLUGIN group_replication SONAME ‘group_replication.so’;

Then, start the plugin to join server2 to the group:

mysql> START GROUP_REPLICATION;

You  can confirm the status of the group by running the command below on server2:

mysql> SELECT MEMBER_ID,MEMBER_HOST,MEMBER_STATE FROM performance_schema.replication_group_members;

Output:

+————————————–+————-+————–+
| MEMBER_ID                            | MEMBER_HOST | MEMBER_STATE |
+————————————–+————-+————–+
| 18cf9650-cde5-11e8-9e26-560001b743c7 | 192.0.2.1   | ONLINE |
| 210cc012-cdf4-11e8-8be1-560001b74419 | 192.0.2.2   | ONLINE |
+————————————–+————-+————–+

As you can see from the output above, we now have two members in the group. To confirm if server2 was able to pick up data from server1, we can run the command below and see whether the sample database that we created above was synchronized succesfully:

mysql> show databases;

Output:

+——————–+
| Database           |
+——————–+

| test_replication   |
+——————–+

Step 7: Configuring server3

Just like we have done on server2, we can configure server3 and join it to the group. Before doing this, make sure you have installed MySQL community on server3 as discussed in step 1.

Then, edit the configuration file of server3 using nano text editor:

$ sudo nano /etc/mysql/my.cnf

Paste the below configuration information at the end of the file. Remember to replace 192.0.2.3 with the correct private address assigned to your server3 virtual machine instance.

[mysqld]

bind-address= 0.0.0.0
server_id=3
gtid_mode=ON
enforce_gtid_consistency=ON
binlog_checksum=NONE

log_bin=binlog
log_slave_updates=ON
binlog_format=ROW
master_info_repository=TABLE
relay_log_info_repository=TABLE

transaction_write_set_extraction=XXHASH64
loose-group_replication_group_name=”99bfc355-cd41-11e8-ba46-5600018c8695″
loose-group_replication_start_on_boot=off
loose-group_replication_local_address= “192.0.2.3:33061”
loose-group_replication_group_seeds= “192.0.2.1:33061, 192.0.2.2:33061, 192.0.2.3:33061”
loose-group_replication_bootstrap_group=off

report_host=192.0.2.3

Press CTRL+X, Y and hit Enter to save the file.Then, restart MySQL server for the changes to take effect:

$ sudo service mysql restart

Next, log in to MySQL on server3:

$ sudo mysql -uroot -p

Enter your MySQL password when prompted and hit Enter. We need to create a user for the group replication channel on server3 just like we did on server1 and server2:

mysql> SET SQL_LOG_BIN=0;
mysql> CREATE USER ‘rep_user’@‘%’ IDENTIFIED BY ‘PASSWORD’;
mysql> GRANT REPLICATION SLAVE ON *.* TO ‘rep_user’@‘%’;
mysql> FLUSH PRIVILEGES;
mysql> SET SQL_LOG_BIN=1;
mysql> CHANGE MASTER TO MASTER_USER=‘rep_user’, MASTER_PASSWORD=‘PASSWORD’      FOR CHANNEL ‘group_replication_recovery’;

Next, run the command below to install the Group Replication plugin:

mysql>INSTALL PLUGIN group_replication SONAME ‘group_replication.so’;

Then start the Group Replication plugin to join server3 the group:

mysql> START GROUP_REPLICATION;

We can then confirm the status of our group using the commands below:

mysql> SELECT MEMBER_ID,MEMBER_HOST,MEMBER_STATE FROM performance_schema.replication_group_members;

Output:

+————————————–+————-+————–+
| MEMBER_ID                            | MEMBER_HOST | MEMBER_STATE |
+————————————–+————-+————–+
| 1634bce6-cdfb-11e8-8f8d-560001b74425 | 192.0.2.1   | ONLINE |
| 18cf9650-cde5-11e8-9e26-560001b743c7 | 192.0.2.2   | ONLINE |
| 210cc012-cdf4-11e8-8be1-560001b74419 | 192.0.2.3   | ONLINE |
+————————————–+————-+————–+

As you can see above, our group has 3 members like we expected and our Group Replication setup is working like expected.

We can confirm if server3 was able to synchronize data from the group by running the command below:

mysql> show databases;

Output:

+——————–+
| Database           |
+——————–+

| test_replication   |
+——————–+

The database that we created is already synchronized and our Group Replication is working as expected.

Conclusion

In this guide, we have taken you through the steps of setting up and configuring MySQL group replication on Ubuntu 18.04 server.

If you have followed along, you are able to create a fault-tolerant database cluster using a shared-nothing architecture that ensures high availability for your database server.

New to VPS hosting, sign up with Digital Ocean and get $100 worth of free trial credit.

Faiba 4G Network and MiFi Router Review

Are you looking for a honest Faiba 4G review. Then, this guide will answer most of your questions.

Faiba_4G_Review

Faiba 4G network is a unique internet service product offered by Jamii Telecom. The company guarantees the fastest and most reliable broadband service in major towns in Kenya.

Some Facts about Faiba 4G Internet Service

The Faiba 4G network uses the regular mobile network but it works on 4G only. This means increased speed to the end users.

To use the product, you require a 4G sim card from Jamii Telecom and a phone or any device that supports 4G network. Luckily, since most phones in Kenya can only support 3G network, Jamii Telecom sells a MiFi(Mobile Wifi) router alongside their sim cards.

The MiFi router is manufactured by Huawei and it is quite a good device that can connect up to 12 users simultaneously on the internet. It goes for around Kshs. 5,500/=

Faiba 4G Bundles

The Faiba 4G bundles are quite cheap compared to the other networks bearing in mind that they have the fastest network.

  • A 1GB daily bundle costs Kshs. 50/=
  • If you want a weekly bundle, you will have to part with Kshs. 300 and get a whopping 8GB
  • For those who like monthly data plans, you can grab 25GB at Kshs. 1,000/=

Faiba 4G Coverage

The areas below are covered by Faiba 4G network

Nairobi Area:

  • Nairobi
  • Rongai
  • Kiserian
  • Ngong Town
  • Athi River
  • Syokimau
  • Kitengela
  • Ruiru
  • Kiambu
  • Kikuyu
  • Juja
  • Limuru

Machakos

  • Town Center
  • Miwani

Thika

  • Town center
  • Makongeni
  • Kiganjo
  • Landless

Nakuru

  • Engoshura Jandu
  • Barracks
  • Koinange
  • Lanet
  • Milimani
  • Naka
  • Pangani
  • Railway Station
  • Unga Estate
  • Bondeni
  • Eden
  • Kiamunyi
  • Kiamunyeki

Eldoret

  • Testimony
  • West Indies
  • Kapsoya
  • Railways
  • Kimumu
  • East
  • Langas

Kisumu

  • Manyatta 2
  • Migosi
  • Mountain View
  • Stadium
  • Nyalenda
  • Mamboleo
  • Carwash
  • Milimani
  • Industrial Area

Mombasa

  • NSSF
  • Mtwapa
  • Makaburini
  • Bamburi Cement
  • Voyager
  • Mbaraki
  • Shimanzi road
  • Makadara
  • Kiembeni
  • Mikindani
  • Mombasa Polytechnic
  • Bombolulu

Faiba 4G Agents and Shops

There are many places where you can buy the Faiba 4G product. I will list just a few of them but I will keep adding more shops to the list:

Nairobi

Compnet Vedic Hse room 201/202

Mama Ngina St., Nairobi Kenya

0722 356620/ 0722648222

Kiambu

Naivas Naivakom Kiambu

Thika

Tuscom – on Tuskys Chania(near Gatitu). This is where I bought my device before writing this Faiba 4G MiFi router review.

Thika Road

Samsung Shop TRM

Limuru

Naivas Naivakom Limuru

Athi River

Tuskys Tuscom Athi River

Syokimau

Naivas Naivakom Syokimau

Kitengela

Naivas Naivakom Kitengela

Buru buru

Tuskys Tuscom Buru Buru

Ngong Town

Naivas Naivakom Ngong Town

Machakos

Naivas Naivakom Machakos

Mombasa

Naivas Naivakom Nyali

Nakuru

Naivas Naivakom Nakuru

Kisumu

Tuskys Tuscom Kisumu

Managing your Faiba 4G MiFi

When you purchase the Faiba 4G MiFi device, you will have to download Huawei HiLink app on your smartphone.
You will use this software to  change the wifi password, block users, restart the device remotely and even view the battery usage in percentage.

Purchasing Bundle for Jamii Telcom Faiba 4G Router

Jamii Telecom has a very good app available on Googe Play for managing the credit or data bundles for your account. See the image below:
Faiba_4G_App_Google_Play
The procedure for purchasing bundles is quite straightforward.
You simply press Buy Bundle and you get prompted to choose a bundle. Then, enter your Mpesa PIN and after a few seconds, your account will be updated with the bundles purchased.

Using your Faiba 4G MiFi on a Computer or Laptop

As mentioned earlier the MiFi 4G router from Jamii Telcom supports up to 12 users. If you are using a computer or a laptop, you can simply connect the device to your machine via a USB cable that comes with the device.
Faiba_4G_Review
Alternative, if your laptop or desktop PC has a Wifi receiver, you simply search your MiFi network and connect to it. From there you can start enjoying very great speed even for streaming YouTube videos.

Conclusion

Faiba 4G has satisfied the ever increasing demand for fast, reliable stable and affordable internet for all people in Kenya.
I believe Jamii Telecom is doing their best to cover most parts in Kenya. So far, if you are in major towns, you can enjoy an internet speed that you have never imagined it existed in Kenya. I hope you enjoyed this Faiba 4G review.

How to Setup WordPress Website with Apache, MySQL and PHP on Ubuntu 18.04 VPS

Since May 2003, WordPress has remained the most popular, stable, secure and easy to use Content Management System (CMS) for setting up websites.

The free Open-source software is fully built-in and comes with thousands of beautiful themes and plugins for extended functionalities.

WordPress WYSIWYG interface is browser-based and does not require complicated FTP or HTML coding software applications to launch a website.

Due to its clean and simple code, the CMS is loved by all major search engines because it is easier to index.

WordPress is based on PHP and MySQL and runs on most popular web servers including Apache and Nginx.

On a shared hosting, WordPress can be installed by automatic script installers such as Softaculous.

However, the installation method on a VPS hosting  takes a new approach and can be done with just a few and simple shell commands.

This is a step-by-step guide on setting up a WordPress website with  Apache, MySQL and PHP on Ubuntu 18.04 VPS.

Prerequisites

  • A VPS account running Ubuntu 18.04 Operating System. Sign up with Digital Ocean and get free trial credit worth $100 to configure this article and test other cloud products.
  • A domain name (e.g. example.com). You can buy a domain name from a registrar of your choice(e.g. Namecheap).
  • A non-root user that can perform sudo tasks for your Ubuntu 18.04 Server.

Step 1: Point your Domain Name DNS records to your VPS

The first step is to point the DNS records of your domain name to your VPS . When visitors enter your domain name on a browser, they should be routed to the IP address associated with your VPS account.

You should ask your VPS provider about the correct DNS records to use if you are in doubt.

For instance, if you are running a VPS from Vultr, the DNS records look like these:

  • ns1.vultr.com
  • ns2.vultr.com

Step 2: Connecting to Your VPS Server

SSH to your Ubuntu 18.04 server using the public IP address (e.g. 198.18.0.22) associated with your VPS instance.  You can do this via the Command Line Interface (CLI) that ships with Linux or Mac. If you are running Windows on your local computer, consider downloading PuTTY SSH client.

Step 3: Installing Apache Web Server

The first software we are going to install is Apache. It’s an Open source web server application that runs the world’s busiest sites. Apache can handle large traffic and has lots of built-in security features and expandable modules.

To install Apache, first update the package information list on your Ubuntu server using the command below:

$ sudo apt-get update

Then, pull Apache from Ubuntu’s software repository using the command below:

$ sudo apt-get install apache2 php libapache2-mod-php

Press Y and hit Enter when prompted to confirm the installation.

Step 4: Initializing WordPress Website Directory Structure

Apache has a special feature called Virtual Hosts. This advanced feature allows you to host unlimited websites on a single Linux machine.

Before we create the Virtual Host configuration file, we must initialize the directory for holding our website files.

We have to create the directory under the /var/www/ folder using the command below:

$ sudo mkdir -p /var/www/example.com/public_html

Step 5: Creating a Virtual Host for the WordPress Website

When you install Apache, a default Virtual host (000-default.conf) is created under the /etc/apache2/sites-available directory. To keep things simple, we will create our own virtual host to run our WordPress site.

Please note, virtual hosts configuration files must end with a ‘.conf’ extension. So let’s create the configuration file for our domain name www.example.com

$ sudo nano /etc/apache2/sites-available/example.com.conf

Then, copy and paste the below content on that file:

<VirtualHost *:80>

    ServerAdmin admin@example.com

    ServerName example.com

    ServerAlias www.example.com

    DocumentRoot /var/www/example.com/public_html

    ErrorLog ${APACHE_LOG_DIR}/error.log

    CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory /var/www/example.com/public_html>

     Options -Indexes +FollowSymLinks -MultiViews

     AllowOverride All

     Require all granted

  </Directory>

</VirtualHost>

Press CTRL+X, Y, and Enter to save the file.

We need to disable the default virtual host and enable the one we have just created, run the commands below:

$ sudo a2dissite 000-default.conf
$ sudo a2ensite example.com.conf

Restart Apache web server

$ sudo systemctl restart apache2

Step 6: Installing MySQL Database Server

WordPress relies on MySQL to store data. Apart from photos, plugins, and themes, post and web pages are stored in the MySQL relational database.

Like WordPress and Apache, MySQL is free and Open-source. It is also available on the Ubuntu’s software repository and we can install it using the apt command:

$ sudo apt-get install mysql-server

Press Y and hit Enter when prompted to confirm the installation

Step 7: Securing MySQL Server

MySQL installation is not secure by default. It comes with some test databases and other settings that we must disable. To do this, run the command below:

$ sudo mysql_secure_installation

You will get a prompt to answer multiple questions. We have prepared the correct responses, just follow the settings below:

Setup 'validate password' plugin? [Y/N] Y
Password Validation Policy Level: 2
Root Password: PASSWORD
Re-enter password: REPEAT PASSWORD
Continue with the password provided? Y
Remove anonymous users? [Y/N] Y
Disallow root login remotely? [Y/N] Y
Remove test database and access to it? [Y/N] Y
Reload privilege tables now? [Y/N] Y

If all goes well, you will get a success message.

Step 8: Creating a WordPress Database and User

Next, we are going to create a database and username for our WordPress software. First, log in to the MySQL command line interface using the command below:

$ sudo mysql -u root -p

Enter the root password of your MySQL server when prompted and hit Enter.

Then, on the command prompt that appears, enter the below SQL command to create a database:

mysql> Create database wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

To create a database user, run the command below:

mysql>Create user  'wp_user'@'localhost' IDENTIFIED BY 'PASSWORD';

Then, assign all privileges to the ‘wordpress’ database to the user we have created above using the command below:

mysql> Grant all privileges on wordpress.* to  'wp_user'@'localhost';

Flush privileges for the changes to take effect:

mysql> Flush privileges;

Exit from the MySQL command line interface:

mysql> Exit;

Step 9: Installing PHP on Ubuntu 18.04 Server

WordPress is written in PHP language and we must install the software on our Ubuntu 18.04 server in order for the application to function.

We are also going to install all the required PHP modules that WordPress require.

We can install all the software and modules in one line using the command below:

$ sudo apt-get install php php-cli php-common php-mbstring php-gd php-intl php-xml php-mysql php-zip php-curl php-xmlrpc

Restart Apache web server for the changes to take effect:

$ sudo systemctl restart apache2

Step 10: Downloading and Installing WordPress on Ubuntu 18.04 VPS

We now have a web server, a database for our WordPress software and PHP scripting language. We can now go ahead and download WordPress.

First, cd to the ‘tmp’ directory:

$ cd /tmp

Then, grab the latest WordPress version using wget command:

$ wget -c http://wordpress.org/latest.tar.gz

To unzip the WordPress installation files to the root directory of the virtual host that we created earlier, run the commands below:

$ sudo tar -xzvf latest.tar.gz
$ sudo cp -r wordpress/.  /var/www/example.com/public_html/

Apache runs under the www-data user, we need to grant the web server full permissions to control our website’s file. Run the command below:

$ sudo chown -R www-data:www-data /var/www/example.com/public_html

Then, we can set the appropriate permissions to ensure the outside world has read and execute permissions only:

$ sudo chmod -R 755 /var/www/example.com/public_html

To make sure that newly created files and folders inherit the correct permissions, we can run the command below:

$ sudo find /var/www/example.com/public_html -type d -exec chmod g+s {} \;

Step 11: Finalizing WordPress Installation on Ubuntu 18.04 Server

We now have WordPress installation files on the root of our website. However, we need to configure the database settings on the WordPress configuration files.

So type the command below to copy wp-config.php file from the default wp-config-sample.php file:

$ sudo cp /var/www/example.com/public_html/wp-config-sample.php /var/www/example.com/public_html/wp-config.php

Then, open the new configuration file that we have copied using a nano editor:

$ sudo nano /var/www/example.com/public_html/wp-config.php

Look for the values:

define('DB_NAME', 'database_name_here');
/** MySQL database username */
define('DB_USER', 'username_here');
/** MySQL database password */
define('DB_PASSWORD', 'password_here');

And change them to:

define('DB_NAME', 'wordpress');
/** MySQL database username */
define('DB_USER', 'wp_user');
/** MySQL database password */
define('DB_PASSWORD', 'PASSWORD');

Remember to replace PASSWORD with the correct value.

Before you close the file add the line below at the top:

<?php

And the line below at the bottom

?>

If you don’t add the two lines, PHP will not be able to parse the configuration file.

On a browser, enter your domain to finalize WordPress installation. If you followed all the steps, you should see the below web page:

Configuring WordPress with Apache, MySQL and PHP on Ubuntu 18.04 VPS

Congratulations! Your WordPress site is now installed. Just follow the wizard to complete the final settings.

Finally, you can create new posts, add a new web page or probably change the WordPress theme to match the look and feel of your company brand.

Conclusion

We have shown you how to install WordPress with Apache, MySQL, and PHP on Ubuntu 18.04 server.

Remember, you can run as many WordPress sites as required on your VPS plan by leveraging the power of Apache Virtual Host feature.

Sign up with Digital Ocean today and enjoy up to $100 worth of free trial credit to test this article and other cloud products.