Set up a blasting fast hosting solution with nginx and MariaDB

Nginx LogoWhen you need a fast and reliable hosting solution, you should consider which web server and database system to use. Many sites find the combination of nginx (pronounced “engine x”) and MariaDB to be an optimal solution. Let’s see how to install and configure the applications to work together.

Nginx is a stable, lightweight, and fast open source web server. Nowadays it is the second most popular web server overall, after Apache. More and more system architects are installing it on their servers to support heavy resource demands and efficiently handle the traffic volume at popular web sites. Nginx can also serve as a reverse proxy service in front of Apache, and handle load-balancing.

For its part, MariaDB is a fast and a reliable database engine. Though it is a binary drop-in replacement of MySQL, the database from which it was forked, it has many new features and improvements in terms of speed, stability, and performance.

To start hosting web sites that work with nginx and MariaDB, first check your Linux distribution and kernel versions: # cat /etc/redhat-release && uname -a.

Both nginx and MariaDB are available by default for Debian and Ubuntu Linux distributions. MariaDB also comes by default in Fedora since Fedora 19, and you can setup up nginx in Fedora as well. In this post we’ll focus on the setup under CentOS, since it is one of the most popular choices for web hosting servers. The approach for the other Linux distributions is similar; detailed instructions can be found in their official documentation.

Since the latest nginx package is not included in Yum’s default repository, you should get its RPM file from the EPEL (Extra Packages for Enterprise Linux) repository. Install EPEL and the Remi repositories:

# rpm -Uvh
# rpm -Uvh

Download and update all the metadata for the new Yum repositories by running # yum makecache, then install nginx with the command # yum install nginx -y.

You can alter nginx’s configuration to suit your needs by editing the /etc/nginx/nginx.conf file. For example, you can change the default number of the working processes to match the number of the CPU cores on your server, then start the service:

# grep processor /proc/cpuinfo
processor       : 0
processor       : 1

# sed -i "s/worker_processes.*/worker_processes  2;/" /etc/nginx/nginx.conf

# /etc/init.d/nginx start
Starting nginx:                                            [  OK  ]

Enable the nginx service to start automatically after the server’s boot process by running # chkconfig nginx on, just as you would for any services that should be started on system reboot.

Next, install MariaDB. Using the output of the # cat /etc/redhat-release && uname -a command, generate the necessary MariaDB repository file for your platform through the project’s online tool. Save it in the /etc/yum.repos.d/ folder:

# cat /etc/yum.repos.d/MariaDB.repo
# MariaDB 10.1 CentOS repository list - created 2014-07-17 16:18 UTC
name = MariaDB
baseurl =

Now you can install MariaDB – # yum makecache && yum install MariaDB-server MariaDB-client -y – start the service – # /etc/init.d/mysql start – and make sure it will run after a server reboot – # chkconfig mysql on. You can check the MariaDB version as well:

# mysql -V
mysql  Ver 15.1 Distrib 10.1.0-MariaDB, for Linux (x86_64) using readline 5.1

Because nginx does not have a native PHP processing mechanism, you must configure nginx to work with PHP via the FastCGI processing manager. To get the latest PHP package and necessary dependencies, run # yum --enablerepo=remi install php-fpm php-mysqlnd -y.

Next, modify the nginx and PHP configuration to allow nginx to load PHP scripts. Nginx listens for FastCGI requests through a Unix socket. Edit the /etc/php-fpm.d/www.conf file and change the values of several lines as shown below:

listen.owner = nobody = nobody
listen.mode = 0666

This gives the Unix socket on which PHP-FPM (PHP FastCGI processing manager) listens the correct ownership and permissions to allow connections from the nginx web server. Restart the PHP FastCGI processing manager to create the necessary socket file:

# /etc/init.d/php-fpm restart
Stopping php-fpm:                                          [  OK  ]
Starting php-fpm:                                          [  OK  ]
# ls -la /var/run/php5-fpm.sock
srw-rw-rw- 1 nobody nobody 0 Aug  3 14:43 /var/run/php5-fpm.sock

Now you can create a virtual host for your site. Suppose you want to set a virtual host for your domain named, and the document root for the website is /usr/share/nginx/html/mysite. Open the /etc/nginx/conf.d/virtual.conf file and configure it like the following:

server {
    listen       80;

    location / {
        root   /usr/share/nginx/html/mysite;
        index  index.php index.html index.htm;
location ~ .php$ {
        root   /usr/share/nginx/html/mysite;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;

This tells the web server how to handle web requests for your domain, and from which location on the server to deliver the result. Restart the web services to apply the new configuration.

To see the changes in action, create a simple PHP script to establish a connection to your MariaDB engine and read data from a sample database table. You can create the database, a database user with the necessary privileges, and a populated table through the following queries:

# mysql
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MariaDB connection id is 4
Server version: 10.1.0-MariaDB MariaDB Server

Copyright (c) 2000, 2014, Oracle, SkySQL Ab and others.

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

MariaDB [(none)]> create database mysite;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> create user mysite_user;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> grant all privileges on mysite.* to 'mysite_user'@'localhost' identified by 'MyadmInp@Ss';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> use mysite;

MariaDB [mysite]> CREATE TABLE `continents` (   `id` INT NOT NULL AUTO_INCREMENT,   `code` CHAR(2) NOT NULL,   `name` VARCHAR(255) ,   PRIMARY KEY (`id`) );
Query OK, 0 rows affected (0.41 sec)

MariaDB [mysite]> INSERT INTO `continents` (`code`,`name`) VALUES   ('AF', 'Africa'),   ('AS', 'Asia'),   ('EU', 'Europe'),   ('NA', 'North America'),   ('SA', 'South America'),   ('OC', 'Oceania'),   ('AN', 'Antarctica');
Query OK, 7 rows affected (0.08 sec)
Records: 7  Duplicates: 0  Warnings: 0

To list all the content of the new table through a PHP script, write code that establishes a connection to your MariaDB database with the details you entered above, runs a SELECT query on the continents table, and prints the results with a looping function:

$dbcon=mysql_connect($dbserver,$dbuser,$dbpassword) or die("Unable to Connect");
mysql_select_db($dbname) or die("Could not open the db");
$result = mysql_query("SELECT * FROM continents");
while($row = mysql_fetch_array($result)) {
  echo $row['id'] . " " . $row['code'] . " " . $row['name'];
  echo "";

Once you have nginx and MariaDB set and ready to work in collaboration on your server, you can provide a stable, resource-effective, and fast hosting environment for your clients.