21.4.14

How To Install and Use Memcache on Ubuntu 12.04

How To Install and Use Memcache on Ubuntu 12.04 -> 13.10

Memcache is a system that works to speed up virtual private servers by caching server information. The program allows you to allocate a specific amount of the server ram toward caching recently queried data for a certain amount of time. Once the data is requested again, memcache speeds up the process of retrieving it by displaying the cached information instead of generating the result from the database.


Setup

The steps in this tutorial require the user to have root privileges. You can see how to set that up in the Basic Users Tutorial.

Before starting off, it’s a good idea to update apt-get to make sure that all of the packages we download to the VPS are up to date.
sudo apt-get update

Additionally, you should have MySQL and PHP installed on the virtual server.
sudo apt-get install mysql-server php5-mysql php5 php5-memcache

Install Memcache


Installing memcache takes several steps.

To start, install memcached via apt-get.
sudo apt-get install memcached

The next step is to install php-pear, the repository that stores memcache.
sudo apt-get install php-pear

If you do not have a compiler on your server, you can download build-essential in order to install memcache:
sudo apt-get install build-essential

Finally use PECL (PHP Extension Community Library) to install memcache:
sudo pecl install memcache

Say yes by pressing enter during the installation when you are asked if you would like to “Enable memcache session handler support? [yes] :”

Once you have completed the installation of memcache with PECL on the VPS, add memcached to memcache.ini:
echo "extension=memcache.so" | sudo tee /etc/php5/conf.d/memcache.ini

Now you are ready to start using Memcache.

Confirm Memcache and See Stats


After Memcache is downloaded, you can check that it has been installed by searching for it:
ps aux | grep memcache

Additionally, you can see the memcache stats by typing:
 echo "stats settings" | nc localhost 11211

Step Three—How Memcache Works


Memcache works by redirecting code to first attempt to retrieve data from the cache before querying the server’s database. The cache populates by saving recently retrieved server data for a certain amount of time. By caching recently requested information, future queries do not have to go through the longer process of retrieving the information from a database and can, instead, access it through the cache.

The memcache page shows this abbreviated code on its homepage to summarize the memcache process:
function get_foo(foo_id)
    foo = memcached_get("foo:" . foo_id)
    return foo if defined foo

    foo = fetch_foo_from_database(foo_id)
    memcached_set("foo:" . foo_id, foo)
    return foo
end

A Simple Memcache Example


This section will set up a simple php script to use memcache for retrieving a single value originally found in a mysql table.

The following steps set up a mysql user who can access the appropriate database, create a table to query, and insert the one value that we will test in the new mysql table.

Log into mysql: mysql -u root -p and execute the following commands:

use test;

grant all on test.* to test@localhost identified by 'testing123';

create table example (id int, name varchar(30));

insert into example values (1, "new_data");

exit;

Once you have exited MySQL, create the memcache script file:
nano memtest.php

We are now going to build up the php script step by step (the entire script will be at the end of the section):

  • Start off by creating a new persistent connection with memcache, which runs on memcache’s default port, 11211.
    <?php
    $meminstance = new Memcache();
    $meminstance->pconnect('localhost', 11211);

  • The next step is to connect to the new mysql database with the user that we created earlier:
    mysql_connect("localhost", "test", "testing123") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());

  • After that, go ahead and create the query that we will pose to the server, as well as provide a key to identify that specific action:
    $query = "select id from example where name = 'new_data'";
    $querykey = "KEY" . md5($query);

  • The script first searches the cache for the answer to the query. If the result does not exist, the script reroutes the question to the original database. Once the query has been answered by the original database, the script stores the result in memcache, using the “set” command-- which both saves it and allows the user to designate the number of seconds that it should remain in the cache (600 would save it in the cache for 10 minutes).

    When we run the script for the first time, it will inform us that the data was collected from the mysql database. However, as it does so, it stores the information in the cache, so that a second run of the script retrieves it from the cache and lets the user know.

    In 10 minutes the cache is emptied once more and running the script will make it access the database once again.

    $result = $meminstance->get($querykey);
    
    if (!$result) {
           $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
           $meminstance->set($querykey, $result, 0, 600);
    print "got result from mysql\n";
    return 0;
    }
    
    print "got result from memcached\n";
    return 0;
    
    ?>

Altogether the script looks like this:
<?php
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);

mysql_connect("localhost", "test", "testing123") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$query = "select id from example where name = 'new_data'";
$querykey = "KEY" . md5($query);

$result = $meminstance->get($querykey);

if (!$result) {
       $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
       $meminstance->set($querykey, $result, 0, 600);
print "got result from mysql\n";
return 0;
}

print "got result from memcached\n";
return 0;

?>

Running the script on the command line produces the following results:
# php memtest.php 
got result from mysql

# php memtest.php 
got result from memcached

# php memtest.php 
got result from memcached

Conclusion


This tutorial covers speeding up the retrieval of data from a database by connecting it to memcache. However, do keep in mind that memcache’s strengh originates from the fact that is a cache—it is not a datastore. When using memcache, do not expect it to replace a database. Because memcache only holds values for a set length of time for a given key, you may not always find the information you need cached, and in cases like these, having the original server database is imperative.

Nevertheless, memcache is a very useful program and can do a lot to increase the server efficiency.

If you have any other questions about Memcache, feel free to ask about specifics on our forum.



By Etel Sverdlov

How To Add Swap on CentOS 6

How To Add Swap on CentOS 6

Linux RAM is composed of chunks of memory called pages. To free up pages of RAM, a “linux swap” can occur and a page of memory is copied from the RAM to preconfigured space on the hard disk. Linux swaps allow a system to harness more memory than was originally physically available. 

However, swapping does have disadvantages. Because hard disks have a much slower memory than RAM, server performance may slow down considerably. Additionally, swap thrashing can begin to take place if the system gets swamped from too many files being swapped in and out.

Check for Swap Space


Before we proceed to set up a swap file, we need to check if any swap files have been enabled by looking at the summary of swap usage.
swapon -s

If nothing is returned, the summary is empty and no swap file exists.

Check the File System


After we know that we do not have a swap file enabled, we can check how much space we have on the server with the df command. The swap file will take 512MB— since we are only using up about 7% of the /dev/hda, we can proceed.
df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/hda              20642428   1347968  18245884   7% /

Create and Enable the Swap File


Now it’s time to create the swap file itself using the dd command :
sudo dd if=/dev/zero of=/swapfile bs=1024 count=512k

“of=/swapfile” designates the file’s name. In this case the name is swapfile. 

Subsequently we are going to prepare the swap file by creating a linux swap area:
sudo mkswap /swapfile

The results display:
Setting up swapspace version 1, size = 536866 kB

Finish up by activating the swap file:
sudo swapon /swapfile

You will then be able to see the new swap file when you view the swap summary.
 swapon -s
Filename    Type  Size Used Priority
/swapfile                               file  524280 0 -1

This file will last on the server until the machine reboots. You can ensure that the swap is permanent by adding it to the fstab file.

Open up the file:
sudo nano /etc/fstab

Paste in the following line:
/swapfile          swap            swap    defaults        0 0


To prevent the file from being world-readable, you should set up the correct permissions on the swap file:
chown root:root /swapfile 
chmod 0600 /swapfile

How To Configure Swappiness


The operating system kernel can adjust how often it relies on swap through a configuration parameter known as swappiness. To find the current swappiness settings, type:
cat /proc/sys/vm/swappiness
60

Swapiness can be a value from 0 to 100. Swappiness near 100 means that the operating system will swap often and usually, too soon. Although swap provides extra resources, RAM is much faster than swap space. Any time something is moved from RAM to swap, it slows down.

A swappiness value of 0 means that the operating will only rely on swap when it absolutely needs to. We can adjust the swappiness with the sysctlcommand:
sysctl vm.swappiness=10
vm.swappiness=10

If we check the system swappiness again, we can confirm that the setting was applied:
cat /proc/sys/vm/swappiness
10

To make your VPS automatically apply this setting every time it boots up, you can add the setting to the /etc/sysctl.conf file:
sudo nano /etc/sysctl.conf
# Search for the vm.swappiness setting.  Uncomment and change it as necessary.
    vm.swappiness=10


By Etel Sverdlov

How To Add Swap on Ubuntu 12.04

How To Add Swap on Ubuntu 12.04, Ubuntu 12.10, Ubuntu 13.10

Linux RAM is composed of chunks of memory called pages. To free up pages of RAM, a “linux swap” can occur and a page of memory is copied from the RAM to preconfigured space on the hard disk. Linux swaps allow a system to harness more memory than was originally physically available.

However, swapping does have disadvantages. Because hard disks have a much slower memory than RAM, virtual private server performance may slow down considerably. Additionally, swap thrashing can begin to take place if the system gets swamped from too many files being swapped in and out.

Check for Swap Space


Before we proceed to set up a swap file, we need to check if any swap files have been enabled on the VPS by looking at the summary of swap usage.
sudo swapon -s

An empty list will confirm that you have no swap files enabled:
Filename    Type  Size Used Priority

Check the File System


After we know that we do not have a swap file enabled on the virtual server, we can check how much space we have on the server with the df command. The swap file will take 256MB— since we are only using up about 8% of the /dev/sda, we can proceed.
df
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda        20907056 1437188  18421292   8% /
udev              121588       4    121584   1% /dev
tmpfs              49752     208     49544   1% /run
none                5120       0      5120   0% /run/lock
none              124372       0    124372   0% /run/shm

Create and Enable the Swap File


Now it’s time to create the swap file itself using the dd command :
sudo dd if=/dev/zero of=/swapfile bs=1024 count=256k

“of=/swapfile” designates the file’s name. In this case the name is swapfile.

Subsequently we are going to prepare the swap file by creating a linux swap area:
sudo mkswap /swapfile

The results display:
Setting up swapspace version 1, size = 262140 KiB
no label, UUID=103c4545-5fc5-47f3-a8b3-dfbdb64fd7eb

Finish up by activating the swap file:
sudo swapon /swapfile

You will then be able to see the new swap file when you view the swap summary.
swapon -s
Filename    Type  Size Used Priority
/swapfile                               file  262140 0 -1

This file will last on the virtual private server until the machine reboots. You can ensure that the swap is permanent by adding it to the fstab file.

Open up the file:
sudo nano /etc/fstab

Paste in the following line:
 /swapfile       none    swap    sw      0       0 


Swappiness in the file should be set to 10. Skipping this step may cause both poor performance, whereas setting it to 10 will cause swap to act as an emergency buffer, preventing out-of-memory crashes.

You can do this with the following commands:
echo 10 | sudo tee /proc/sys/vm/swappiness
echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

To prevent the file from being world-readable, you should set up the correct permissions on the swap file:
sudo chown root:root /swapfile 
sudo chmod 0600 /swapfile



By Etel Sverdlov

How To install and Start Using Lithium on Ubuntu 12.04 VPS

How To install and Start Using Lithium on Ubuntu 12.04 VPS

Lithium is a full stack PHP framework for developing web applications. Based on the Model-View-Controller (MVC) architecture, it is built for PHP 5.3+ and integrates with the latest storage technologies like MongoDB or CouchDB.
It is designed to offer both great project organization as well as the possibility to code out of the framework as you develop your own unique web application. Additionally, it features a robust plugin system that allows you to use your favorite components from outside the framework (such as Twig for templating or Doctrine2 for ORM).
In this tutorial we will look at how we can install Lithium on our VPS, as well as get started with a simple web application. For that I assume you already have your server set up and are running the LAMP stack (Apache, MySQL and PHP). If you don't already, there's a great tutorial on DigitalOcean that can get you set up.

Apache setup


Since we are using Apache as a webserver and Lithium makes heavy use of the .htaccess file for URL rewriting, we'll need to also make sure that Apache will in fact let it do that. If you haven't already done the following steps, you'll need to do them now.
Edit the virtual host file that is responsible for the folder where you will have the application (in our case, let's say the default Apache document root: /var/www):
sudo nano /etc/apache2/sites-available/default
Inside the block marked with this beginning:
<Directory /var/www/>
Make sure that instead of AllowOverride None you have AllowOverride All.
Next thing we need to do is enable mod_rewrite (again if you don't already have it enabled). To check if it's already enabled, use the following command:
apache2ctl -M
If you see "rewrite_module" in the list, you are fine. If not, use the following command to enable the module:
a2enmod rewrite 
After making any changes to either the virtual host file or enabling an Apache module, you have to restart Apache:
sudo service apache2 restart

Installation


Before we begin installing Lithium, let's install Git so we can use it to fetch the framework from GitHub. You can do this with the following 2 commands:
sudo apt-get update
sudo apt-get install git-core
Next, we can clone the Lithium git repository onto our server (while being in our web server's document root: /var/www for Apache):
git clone git://github.com/UnionOfRAD/framework.git site
This will clone the framework repository and place it in a folder called site. Now we can install Lithium as a submodule:
cd site
git submodule init
git submodule update
This will now clone the lithium library as well onto our server in the libraries/lithium/ folder. This will be needed for bootstrapping the application.

Command line


Lithium comes with a command line utility (li3) that helps with code generation, documentation, etc. But to make it usable from anywhere, we'll need to add the console library to the shell path. Open the .bash_profile file located in your home folder (if you don't already have one you can create it):
nano ~/.bash_profile 
And paste the following in it:
PATH=$PATH:/path/to/docroot/lithium/libraries/lithium/console
Make sure you replace the path with the correct path that leads to the console in your case. So in our case it would be:
PATH=$PATH:/var/www/site/libraries/lithium/console
After any such move, you should run the following command to make sure the bash command will take effect:
source ~/.bash_profile
And now test the command to make sure it is working by running it without any options to get its help information:
li3

Database connection


Most web applications need a database to rely on for storage. With Lithium, you can use a wide range of database engines like MySQL, MariaDB, MongoDB, CouchDB etc. For the purpose of setting up our test appplication we will use MySQL, but you are free to experiment with whatever you feel more comfortable. There is more information here about setting it up with MongoDB.
The first thing we need is a database so make sure you have one. If you don't know how to work with MySQL and create your db, read this great tutorial on using MySQL.
To set up a database connection, first edit the bootstrap.php file located in the app/config folder of your application (site/):
nano /var/www/site/app/config/bootstrap.php
Inside this file, if commented, uncomment the following line:
require __DIR__ . '/bootstrap/connections.php';
Then edit the following file:
nano /var/www/site/app/config/bootstrap/connections.php
And uncomment the database configuration found under the following block:
/**
* Uncomment this configuration to use MySQL as your default database.
*/
You'll notice multiple blocks like this for different database engines. Additionally, set your MySQL connection information where appropriate.

Your application


It's time to visit the browser and see what we have so far. You can do so by navigating to your ip/site. There you should see your Lithium application up and running with some information about its status and the server configuration that needs to be made for it to work.
If you see the following message:
Magic quotes are enabled in your PHP configuration
You need to edit the php.ini file on your server:
sudo nano /etc/php5/apache2/php.ini
And paste the following line in it:
magic_quotes_gpc = Off
Then save the file and restart Apache:
sudo service apache2 restart

Model-View-Controller


Since Lithium is a MVC framework, you'll see in the folder structure 3 important folders for that: controllers/, models/ and views/. Let's quickly create our first controller and print Hello world! onto the page with it.
Create a new file in the controllers/ folder called HelloController.php with the following content:
<?php

namespace app\controllers;

class HelloController extends \lithium\action\Controller {
 public function index() {
   echo "Hello World!";
 }
}

?>
You can save the file. What we did here was create a new controller class located in a carefully named file (based on the class name) and that extends the Lithium controller class. Inside, we created an index method that will get called if no parameters are passed when calling this controller. Inside this method we just print out the message.
To access this in the browser, you now have to navigate to your-ip/site/hello and you should see Hello World printed on the page.

Conclusion


In this tutorial, we've seen how to install Lithium PHP and make the necessary server configuration to make it work. We've seen how to connect it to a database (we have not used yet) and created our first controller that simply prints a message onto the page.
In the next tutorial, we will go a bit further and see how the MVC architecture works with Lithium. We'll use Views as well as Models (to illustrate the interaction with our MySQL storage engine).
Article Submitted by: Danny

SQL And NoSQL Databases And Different Database Models

SQL And NoSQL Databases And Different Database Models

Since time immemorial, one of the most heavily needed and relied upon functionality of computers has been the memory. Although the technicalities and underlying implementation methods differ, most computers come equipped with necessary hardware to process information and safe-keep them to be used in future whenever necessary.
In today's world, it is almost impossible to think of any application that does not make use of this ability of machines, whether they be servers, personal computers or hand-held devices. From simple games to business-related tools, including web sites, certain type(s) of data is processed, recorded, and retrieved with each operation.
Database Management Systems (DBMS) are the higher-level software, working with lower-level application programming interfaces (APIs), that take care of these operations. To help with solving different kind of problems, for decades new kinds of DBMSs have been developed (e.g. Relational, NoSQL, etc.) along with applications implementing them (e.g. MySQL, PostgreSQL, MongoDB, Redis, etc).
In this DigitalOcean article, we are going to go over the basics of databases and database management systems. We will learn about the logic behind how different databases work and what sets them apart.

Glossary


1. Database Management Systems


2. Database Models


  1. The Relational Model
  2. The Model-less (NoSQL) Approach

3. Popular Database Management Systems


  1. Relational Database Management Systems
  2. NoSQL (NewSQL) Database Systems

4. A Comparison of SQL and No-SQL Database Management Systems


Database Management Systems


Database Management System is an umbrella term that refers to all sorts of completely different tools (i.e. computer programs or embedded libraries), mostly working in different and very unique ways. These applications handle, or heavily assist in handling, dealing with collections of information. Since information (or data) itself can come in various shapes and sizes, dozens of DBMS have been developed, along with tons of DB applications, since the second half of the 21st century to help in solving different programming and computerisation needs.
Database management systems are based on database models: structures defined for handling the data. Each emerging DBMS, and applications created to actualise their methods, work in very different ways with regards to definitions and storage-and-retrieval operations of said information.
Although there are a large number of solutions that implement different DBMs, each period in history has seen a relatively small amount of choices rapidly become extremely popular and stay in use for a longer time, with probably the most predominant choice since the past couple of decades (or even longer) being the Relational Database Management Systems (RDBMS).

Database Models


Each database system implements a different database model to logically structure the data that is being managed. These models are the first step and the biggest determiner of how a database application will work and handle the information it deals with.
There are quite a few different types of database models which clearly and strictly provide the means of structuring the data, with most popular probably being the Relational Model.
Although the relational model and relational databases are extremely powerful and flexible - when the programmer knows how to use them, for many, there have been several issues or features that these solutions never really offered.
Recently, a series of different systems and applications called NoSQL databases started to gain popularity, expeditiously, with their promise of solving these problems and offering some very interesting additional functionality. By eradicating the strictly structured data keeping style defined within the relational model, these DB systems work by offering a much more freely shaped way of working with information, thus providing a great deal of flexibility and ease -- despite the fact that they come with their own problems, some serious considering the important and indispensable nature of data.

The Relational Model


Introduced in 1970s, the relational model offers a very mathematically-adapt way of structuring, keeping, and using the data. It expands the earlier designs of flat model, network model, et cetera by introducing means of relations. Relations bring the benefits of group-keeping the data as constrained collections whereby data-tables, containing the information in a structured way (e.g. a Person's name and address), relates all the input by assigning values to attributes (e.g. a Person's ID number).
Thanks to decades of research and development, database systems that implement the relational model work extremely efficiently and reliably. Combined with the long experience of programmers and database administrators working with these tools, using relational database applications has become the choice of mission-critical applications which can not afford loss of any information, in any situation -- especially due to glitches or gotchas.
Despite their strict nature of forming and handling data, relational databases can become extremely flexible and offer a lot, granted with a little bit of effort.

The Model-less (NoSQL) Approach


The NoSQL way of structuring the data consists of getting rid of these constraints, hence liberating the means of keeping, querying, and using information. NoSQL databases, by using an unstructured (or structured-on-the-go) kind of approach, aim to eliminate the limitations of strict relations, and offer many different types of ways to keep and work with the data for specific use cases efficiently (e.g. full-text document storage).

Popular Database Management Systems


In this article, our aim is to introduce you to paradigms of some of the most (and more) popular and commonly used database solutions. Although it is hard to reach a numeric conclusion, it can be clearly estimated that for most, the odds lie between a relational database engine, or, a relatively newer NoSQL one. Before we begin with understanding the differences between different implementations of each one of these systems, let us now see what is under-the-hood.

Relational Database Management Systems


Relational Database System takes its name from the model it implements: The Relational Model, which we have discussed previously. Currently, and for quite some time to come, they are and they will be the popular choice of keeping data reliably and safe -- and they are efficient as well.
Relational database management systems require defined and clearly set schemas - which is not to be confused with PostgreSQL's specific definition for the term - in order to accept data. These user-defined formats shape how the data is contained and used. Schemas are much like tables with columns, representing the number and the type of information that belongs to each record; and rows represent entries.
Some popular relational database management systems are:
  • SQLite:
A very powerful, embedded relational database management system.
  • MySQL:
The most popular and commonly used RDBMS.
  • PostgreSQL:
The most advanced, SQL-compliant and open-source objective-RDBMS.
Note: To learn more about NoSQL database management systems, check out our article on the subject: A Comparison Of NoSQL Database Management Systems.

NoSQL (NewSQL) Database Systems


NoSQL database systems do not come with a model as used (or needed) with structured relational solutions. There are many implementations with each working very differently and serving a specific need. These schema-less solutions either allow an unlimited forming of entries, or, a rather an opposing, very simple but extremely efficient as useful key based value stores.
Unlike traditional relational databases, it is possible to group collections of data together with some NoSQL databases, such as the MongoDB. These document stores keep each data, together, as a single collection (i.e. document) in the database. These documents can be represented as singular data objects, similar to JSON and still be quires depending on attributes.
NoSQL databases do not have a common way to query the data (i.e. similar to SQL of relational databases) and each solution provides its own query system.
Note: To learn more about relational database management systems, check out our article on the subject: A Comparison Of Relational Database Management Systems.

A Comparison of SQL and No-SQL Database Management Systems


In order to reach a simpler, understandable conclusion, let us analyse SQL and No-SQL database management systems' differences:
  • Structure and type of data being kept:
SQL/Relational databases require a structure with defined attributes to hold the data, unlike NoSQL databases which usually allow free-flow operations.
  • Querying:
Regardless of their licences, relational databases all implement the SQL standard to a certain degree and thus, they can be queried using the Structured Query Language (SQL). NoSQL databases, on the other hand, each implement a unique way to work with the data they manage.
  • Scaling:
Both solutions are easy to scale vertically (i.e. by increasing system resources). However, being more modern (and simpler) applications, NoSQL solutions usually offer much easier means to scale horizontally (i.e. by creating a cluster of multiple machines).
  • Reliability:
When it comes to data reliability and safe guarantee of performed transactions, SQL databases are still the better bet.
  • Support:
Relational database management systems have decades long history. They are extremely popular and it is very easy to find both free and paid support. If an issue arises, it is therefore much easier to solve than recently-popular NoSQL databases -- especially if said solution is complex in nature (e.g. MongoDB).
  • Complex data keeping and querying needs:
By nature, relational databases are the go-to solution for complex querying and data keeping needs. They are much more efficient and excel in this domain.
Submitted by: O.S. Tezer

How To Install DokuWiki with Nginx on an Ubuntu 12.04 VPS

How To Install DokuWiki with Nginx on an Ubuntu 12.04 VPS

Wiki-style documentation has grown in popularity over the past decade. Community-editable documentation projects offer a system that can distribute the workload among contributors, can be made publicly or privately accessible, and can scale easily.
There are many different wiki applications that each have their strengths depending on your needs. One choice is DokuWiki, which is a very light-weight wiki that can be set up easily. DokuWiki uses a simple file format to store its data, so it does not require you to maintain a database. This makes migrating and scaling trivial.
In this guide, we will discuss how to install DokuWiki with an Nginx server on an Ubuntu 12.04 VPS.

Install Nginx and PHP


As we mentioned above, DokuWiki does not rely on a database like many wikis do. As such, we can forego installing MySQL, MariaDB, PostgreSQL, or other relational database management systems and simply install and configure our web server and processing language.

Install the Web Server


For our web server, we are selecting Nginx. Nginx is easy to install and configure once you are familiar with its syntax. It is also very lightweight, which matches well with our DokuWiki software.
We can find Nginx in Ubuntu's default repositories. Install it now, with apt:
sudo apt-get update
sudo apt-get install nginx
We can then start the server by issuing this command:
sudo service nginx start
Visit your droplet's IP address or domain name in your browser to see the default Nginx page.
server_ip_or_domain
Nginx default page
This verifies that the web server is installed and functioning properly.

Install and Configure PHP


DokuWiki is written in PHP, so we will need to install some components to get this to work well. Unlike Apache, Nginx does not include a module that can handle PHP processing, so instead, it offloads that work onto a separate, dedicated component.
We can install this from apt as well. We will also install a library that will allow our PHP files to process images directly:
sudo apt-get install php5-fpm php5-gd
We need to tighten up some security on the service so that when a request is made for a PHP file that does not exist, the processor does not simply execute other files that may be similar.
Open up the configuration file with root privileges:
sudo nano /etc/php5/fpm/php.ini
Search for and adjust the cgi.fix_pathinfo parameter so that it reads like this:
cgi.fix_pathinfo=0
Save and close the file when you are done.
Next, we'll change our PHP processor to look for connections using a socket instead of a port on our local interface. Open this file with root privileges:
sudo nano /etc/php5/fpm/pool.d/www.conf
Look for the listen directive and change it to use a socket file:
listen = /var/run/php5-fpm.sock
Save and close the file.
Now, configuration on the PHP side is complete. Restart the service to implement the changes we made:
sudo service php5-fpm restart

Configure Nginx


Although we have set up our PHP processor, we have not yet told Nginx to pass PHP requests to that processor. We will have to configure this and some details specific to our DokuWiki installation.
Begin by opening the Nginx default server block file with root privileges:
sudo nano /etc/nginx/sites-available/default
With the comments stripped, this file looks something like this:
server {
    root /usr/share/nginx/www;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /doc/ {
        alias /usr/share/doc/;
        autoindex on;
        allow 127.0.0.1;
        deny all;
    }
}
We will be modifying this significantly. First, we want to tell it to listen to port 80 at the top. You can simply uncomment that line from the file:
server {
    listen 80;

    root /usr/share/nginx/www;
    index index.html index.htm;
. . .
Next, we need to fix the indexing to look for a PHP index file first, before trying to find HTML files, when a directory is requested:
server {
    listen 80;

    root /usr/share/nginx/www;
    index index.php index.html index.htm;
. . .
We should change the name of the server from localhost to the domain name or IP address associated with your server. This will allow it to correctly match web requests:
. . .
    root /usr/share/nginx/www;
    index index.php index.html index.htm;

    server_name server_domain_or_IP_address;

    location / {
. . .
We can comment out the documentation section, since this is configured at the moment to only accept requests originating from the server itself anyways.
We will want to enable some error handling. These lines should already be in your file, and you can simply uncomment them:
. . .
    # location /doc/ {
    #     alias /usr/share/doc/;
    #     autoindex on;
    #     allow 127.0.0.1;
    #     deny all;
    # }
    
    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/www;
    }
. . .
Under the error section, you can set a location block that will hand off our PHP files to our processor. This is somewhat already present in the commented out section, but you should take care to configure it correctly.
In particular, we have a try_files directive that goes along with our PHP configuration choice to discard PHP files that are not exact matches. We also set a fastcgi_param directive to pass the correct script name to our processor to execute.
. . .
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
. . .
Below this, we will find another commented out block that we can uncomment. This will ignore the .htaccess files used by Apache to implement per-directory configuration since Nginx does not use these.
In addition, we will take this opportunity to add an additional block that denies access to a number of directories that DokuWiki uses internally, but which should not be accessible from the web:
. . .
    location ~ /\.ht {
        deny all;
    }

    location ~ /(data|conf|bin|inc)/ {
        deny all;
    }
}
This should bring you to the end of our configuration file. At this point, your file should look similar to this file:
server {
    listen   80;

    root /usr/share/nginx/www;
    index index.php index.html index.htm;

    server_name server_domain_or_IP_address;
    
    location / {
        try_files $uri $uri/ /index.html;
    }

    error_page 404 /404.html;

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

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

    location ~ /\.ht {
        deny all;
    }

    location ~ /(data|conf|bin|inc)/ {
        deny all;
    }
}
Save and close the file.
Now, we need to restart our web server to implement our new configuration:
sudo service nginx restart

Test PHP Processing on our Server


Before we begin the actual DokuWiki configuration, we need to make sure that our server can actually handle PHP files.
If we have not configured our server correctly, our PHP files will simply be downloaded instead of processed. This is certainly not what we want.
To begin, let's create a PHP test file in our server's document root (/usr/share/nginx/www). This file will contain a simple PHP function that displays information about our server:
sudo sh -c 'echo "<?php phpinfo(); ?>" > /usr/share/nginx/www/info.php'
Now, all we have to do is access this file in our web browser by typing our domain name or IP address followed by the path "/info.php":
server_domain_or_IP_address/info.php
If you have configured everything correctly, your PHP script should execute, displaying a page that looks something like this:
PHP info page
If this works correctly, we can remove the file we created and move on to the actual wiki installation:
sudo rm /usr/share/nginx/www/info.php

Install and Configure DokuWiki


Now that we have our web server and PHP processor set up correctly, we can download and install DokuWiki.
In your user's home directory, we can download the latest stable version of DokuWiki by typing these commands:
cd ~
wget http://download.dokuwiki.org/src/dokuwiki/dokuwiki-stable.tgz
This will download a tarball into your current directory. Extract the directory structure by typing:
tar xzvf dokuwiki-stable.tgz
We can now delete the tarball by typing:
rm dokuwiki-stable.tgz
Let's change the name of the directory to whatever path we'd like to access our wiki from. We will use wiki for this guide:
mv doku* wiki
We should move our directory into our web root. This will allow us to access our server by typing our domain followed by /wiki. Move the directory now:
sudo mv wiki /usr/share/nginx/www/
Before we continue, we need to do some additional security steps, or the installer will complain that it cannot access certain areas. Change to the directory you just moved:
cd /usr/share/nginx/www/wiki
The web process needs to have certain access to some files and directories within the wiki structure.
sudo chown -R www-data data
sudo chown www-data lib/plugins/
sudo chown www-data conf
Now, we are ready to install DokuWiki through the web browser using an installer script.
In your browser, go to your domain or IP address followed by the wiki sub directory and install.php:
server_domain_or_IP_address/wiki/install.php
You will be presented with the DokuWiki installation page:
DokuWiki installation page
This is the only configuration page that you need to fill out to get started. Come up with a title and create an administrative account.
One thing to be to be aware of is the ACL policy that you set up. This will decide how people are able to access your wiki:
DokuWiki ACL Policy
Click on the "Save" button at the bottom when you are finished.
At this point, your wiki is installed. You should remove the installation script for additional security. On your server, type:
sudo rm /usr/share/nginx/www/wiki/install.php

Conclusion


You should now have a wiki set up and running on your system. DokuWiki can be easily extended and themed using plugins and templates respectively. Adding content and configuring your site is easy by logging into an administrative account and implementing changes through the interface.
By Justin Ellingwood