This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:
Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.
See Instead:
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.
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.
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
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.
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
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
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):
<?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);
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
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
i got this error message: “PHP Fatal error: Class ‘Memcache’ not found in /home/tommy/www/memtest.php on line 2”
i don’t think i missed anything…
sorry i missed the following step: “sudo apt-get install mysql-server php5-mysql php5 php5-memcache”
problem solved… :) thanks for this awesome tutorial…
Thanks! Glad it worked out =]
Thank You!
hi.how about php connection.is it cashed too.or just the query cahsed?
If you want to speed up PHP connections to MySQL you would need to turn on persistent connections. If persistent connections are enabled when a script finishes executing it doesn’t close the MySQL connection, this allows the next time that the script is called with the same credentials to use an already open connection. This improves script response times as the script no longer has the overhead of opening and then closing the MySQL connection.
Memcache will cache queries so that if a script calls the same query repeatedly after the first time it is called and goes through MySQL to pull the data it will be cached in memcache. Then the next hit to that script will get that information from memcache without needing to run the query, again significantly improving performance.
Does it automatically cache the queries?
This article lays out how to install and use memcache so if you follow the simple guide on how to run your queries using memcache then you will be caching them with memcache before the query hits the DB.
Hi Guys, This method worked for me - this was a really helpful tutorial. Thanks a lot =) Well, i had to Restart the PHP-FPM after the set-up; until then the page was showing “Page temporarily not available.”
sudo /etc/init.d/php5-fpm restart
Just thought of adding this info. Thanks again.
Sorry, but
sudo echo “extension=memcache.so” > sudo /etc/php5/conf.d/memcache.ini
just creates a file sudo in the current directory. The command should read
sudo echo “extension=memcache.so” > /etc/php5/conf.d/memcache.ini
Thank you so much…It worked at the first try for me…
Does mean that port 11211 needs to be opened?
Memcache Object ( [connection] => Resource id #2 )
Code: $meminstance = new Memcache(); $meminstance->pconnect(‘localhost’, 11211); print_r($meminstance);
Help!
@camson If you’re accessing it locally, you shouldn’t need to open up ports in the firewall.
@flaviomuniz I do not see anything wrong in that code, please explain.
I worked the steps of this tutorial shortly after deploying a new droplet and received the following error (after executing “sudo pecl install memcache” and subsequently pressing “Enter”): <pre>running: make sh: 1: make: not found ERROR: `make’ failed</pre> Turns out all I had to do was execute: <pre>sudo apt-get install -y make</pre> and then re-run <pre>sudo pecl install memcache</pre>
Otherwise, everything else was as smooth as a …
There is a mistake in one of the steps and has still not been corrected.
sudo echo “extension=memcache.so” > sudo /etc/php5/conf.d/memcache.ini A user above has already pointed out, this command just creates a file called sudo in the current directory. Please remove the sudo from the second part of the command.
@rajeev1204: Updated the article. Thanks!
Good tutorial. I needed memcache in order to activate caching for a prestashop installation. Thanks.
Hello there! I have been getting optimizing crazy… and would like some advice. I followed the tutorial above and all worked (you guys are awesome with all your tutorials…)
The question, I am running WordPress and already setup Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04: https://www.digitalocean.com/community/articles/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-12-04
Was me doing the above installs foolish since Varnish was already doing most of the work? My admin feels slower after this tutorial.
Should I remove the below packages as they might be using more processor power? php-pear build-essential memcache memcached
Also from the top of the install “sudo apt-get install mysql-server php5-mysql php5 php5-memcache” I likely didnt need to run this but I did… Should I be removing “php5 and php5-memcache”
Sorry for all the questions, maybe some of this is over my head, but you guys make it so easy to work on my Droplet, I maybe went over board?=)
I forgot to mention I had already installed Varnish with this tutorial: https://www.digitalocean.com/community/articles/how-to-install-wordpress-nginx-php-and-varnish-on-ubuntu-12-04
@geet: Even though Varnish and Memcache both cache stuff, they’re two different things. Having both of them should not slow your site down. Did you modify any of your code to use memcached or did you just install it?
my server already running so i think mySQL and PHP already installed. Plz teach me how to check if it installed or not? I dont want to install it 2 times may mess-up my vps. thanks
Additionally, you should have MySQL and PHP installed on the virtual server.
sudo apt-get install mysql-server php5-mysql php5 php5-memcache
@nhatkhoa: If you run the apt-get install command twice, it won’t install them twice so you’re okay. Run the whole command just in case.
Thanks for a great tutorial.
If i run my application on 2x servers/droplets, should I open up 11211?
Also, should I use memcache on all pages that would be used alot? Like my search page and my product page that works like a template, product.php?id= someItem
$meminstance = new Memcache(); $meminstance->pconnect(‘localhost’, 11211); etc etc
Also, is it a good idea to use memcache with APC installed?
@ken.thul: I recommend having a shared memcached server so that both app servers can share the same data. Using it a lot won’t be a problem.
Memcache and APC are two different things. Memcache is a memory object cache while APC is opcode cache.
I also had to install: sudo apt-get install php5-dev (ubuntu 13.04)
I got this message at the end of the installation: “You should add “extension=memcache.so” to php.ini”
Alright, I’m not very experienced with this and I’d appreciate any help. I’m getting the following error-
Memcache::pconnect(): Server localhost (tcp 11211) failed with: Connection refused (111) in /memcache/memcache.php on line 3 PHP Warning: Memcache::pconnect(): Can’t connect to localhost:11211, Connection refused (111) in /memcache/memcache.php on line 3 PHP Warning: Memcache::get(): No servers added to memcache connection in /memcache/memcache.php on line 11 PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /memcache/memcache.php on line 14
I’ve got a remote mysql server running so I’m not sure if that is causing the problems…
@phillip: Is Memcached running? What’s the output of <pre>sudo netstat -plutn | grep 11211</pre>?
How to disable or remove this memcache function? This causing issue to my Prosper202 tracking software.
@tusharthakur123: Delete <code>/etc/php5/conf.d/memcache.ini</code>:
<pre>rm /etc/php5/conf.d/memcache.ini</pre>
I had to change
$meminstance->pconnect(‘localhost’, 11211); to $meminstance->connect(‘localhost’, 11211);
hi,
I have LEMP and wordpress installed. I am assuming this enables me to install and use memcache to my wordpress database? In the section below, do i replace ‘test’ with my wordpress db, user & password details?
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;
@nicholas.ongpl: MySQL and Memcache are not the same. You can’t replace MySQL with memcache on Wordpress (or anything really).
Take a look at <a href=“http://wordpress.org/plugins/wp-ffpc/”>http://wordpress.org/plugins/wp-ffpc/</a>
Sorry Kamal, maybe I could have been clearer. I know MySQL and Memcache are 2 different things. What I mean was ‘A Simple Memcache Example’…
“use test; grant all on test.* to test@localhost identified by ‘testing123’;”
Do I replace test, test@localhost and testing123 with my wordpress database info. i.e. test > wpdb, wpdbusr testing123 > wpdbusrpasswd.
Or is this a separate database for memcache to operate?
Nevermind, I see you need the PECL version for PHP. It isn’t needed in all cases but when accessing it via PHP, it is.
Sorry, I’d remove my previous comment if I could.
@kirby14: I’ve deleted the previous comment :]
If I am running MySQL on a separate VPS will I have to open an additional port (11211) on the FW so queries can use the cached response?
@M. K.: You will only have to open up port 11211 on the server that is running memcached.