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.
Varnish is an HTTP accelerator and a useful tool for speeding up a server, especially during a times when there is high traffic to a site. It works by redirecting visitors to static pages whenever possible and only drawing on the server itself if there is a need for an active process.
Before you start to work through this tutorial, there are a couple prerequisites. You will need a user with root privileges, the LEMP stack, and Wordpress already installed on your server.
You can run through a few of the previous tutorials to make sure that your server is up to speed:
Once you have all of the prerequisites needed to configure varnish with wordpress, you should go ahead and start the process to install Varnish.
The varnish site recommends installing the varnish package through their repository.
You can start that process by grabbing the repository:
sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
The next step is to add the repository to the list of apt sources. Go ahead and open up the file.
sudo nano /etc/apt/sources.list
Once inside the file, add the varnish repository to the list of sources.
deb http://repo.varnish-cache.org/ubuntu/ lucid varnish-3.0
Save and exit.
Finally, update apt-get and install varnish.
sudo apt-get update sudo apt-get install varnish libvarnish-dev
Once you have both nginx and varnish installed, you can start to configure them to ease the load on your virtual private server.
Varnish will serve the content on port 80, while fetching it from nginx which will run on port 8080.
Go ahead and start setting that up by opening the /etc/default/varnish file:
sudo nano /etc/default/varnish
Find the lines under “DAEMON_OPTS”— in the Alternative 2 section, and change the port number by "-a" to 80. The configuration should match the following code:
DAEMON_OPTS="-a :80 \ -T localhost:6082 \ -f /etc/varnish/default.vcl \ -S /etc/varnish/secret \ -s malloc,256m"
That's the only change you need to make there. Save and exit out of that file and open up the default.vcl file:
sudo nano /etc/varnish/default.vcl
This file tells varnish where to look for the webserver content. It should already be configured to have the backend (ie. nginx) listening in on port 8080.
We need to use this file for a secondary purpose. Wordpress is chock full of various cookies that make caching it very difficult. In order to have varnish work as efficiently as possible, we need to tell it to drop all the cookies that don't relate to the admin side of the Wordpress site.
Additionally, we need to tell varnish to remove the cookies that make worpdress very difficult to cache.
The beginning of the default.vcl file should look like this:
[...] backend default { .host = "127.0.0.1"; .port = "8080"; } # Drop any cookies sent to Wordpress. sub vcl_recv { if (!(req.url ~ "wp-(login|admin)")) { unset req.http.cookie; } } # Drop any cookies Wordpress tries to send back to the client. sub vcl_fetch { if (!(req.url ~ "wp-(login|admin)")) { unset beresp.http.set-cookie; } } [...]
Although we have already configured varnish to expect that nginx ports will be running on 8080, the default settings for nginx are still on port 80. We will correct the discrepancy now.
Open up the virtual host file with the Wordpress information. In the previous Wordpress tutorial we simply called it wordpress:
sudo nano /etc/nginx/sites-available/wordpress
The Virtual Host should also be set to port 8080 and be accessible only from the localhost. The updated line looks like this:
[...] server { listen 127.0.0.1:8080; ## listen for ipv4; this line is default and implied [...]
We need to do one last thing prior to starting varnish running on our site, and that is to remove the default enabled virtual host.
sudo rm /etc/nginx/sites-enabled/default
The template will remain in the sites-available directory, should you need it once more.
Once you have made all of the required changes, restart varnish and nginx.
sudo service nginx restart
sudo service varnish restart
Accessing your domain should instantly take you to the varnish cached version, and you can see the details of varnish’s workings on your VPS with this command:
varnishstat
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Former Director of Community at DigitalOcean. Expert in cloud topics including LAMP Stack, CentOS, Ubuntu, MySQL, SSL certificates, and more.
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!
This configuration works for a majority of the time, however I still get a HTTP Error 101 “Connection was reset.” Anyone have any luck and know how to fix this?
You may want to check how many free resources you have on your server, if the config works and occasionally has issues looks like it could be an issue with available RAM, etc.
If you are going to use varnish + nginx solely for serving static sites. it is recommend by varnish dev people that you don’t put varnish in front of nginx as nginx is pretty good at handing static sites without the help of varnish. if you however are setting up php fast-cgi. then you can leverage varnish.
I got this error: Error 503 Service Unavailable Service Unavailable Guru Meditation: XID: 1927329062
Varnish cache server
One question about Varnish, do i have to setup different VCL files for different WP sites or just once?
Can’t seem to get this working with Nginx - keep ending up with Nginx bound to port 80 and 8080…which of course is interfering with Varnish being bound on 80. I can’t find anything in Nginx’s confs or site-enabled that should be pointing at 80.
I think using Tuxlite can make us ease as it can automate the whole install process ;)
I personally don’t think Varnish is needed unless you are pulling 500K+ visitors daily. But if you are looking for another Vanish install, most of the info provided will work here at DO. Look towards the bottom of the page for the Varnish config. http://www.ewanleith.com/blog/900/10-million-hits-a-day-with-wordpress-using-a-15-server
Thanks for your tutorial. I’ve got Varnish set up on port 80 with Apache running on port 8080 on an EC2 instance. Everything seems to work great except when I go to http://mysite.com/wp-admin it redirects to http://mysite.com:8080/wp-admin. I can still log in if I refresh after removing the 8080 part, but it would be great if this didn’t happen. Any ideas how to fix this?
Hey there micah,
Just add the following to your sites-available/default (or what you’ve called that file):
That goes into the server {} - part of your domain. port_in_redirect off;
Furthermore, ensure that your Blog-URL in the WordPress preferences does not show :8080 at the end.
Greetings!
Ok now that I have this up an running, I need to add a second (very small) Wordpress site on the same droplet. Could any one explain how to do that? I’ve done allot of testing from Nignx.org and Stock Overflow articles, but noting seems to work according to the config I’ve created by following this tutorial. Thanks!
@michael You can just duplicate the server{} virtualhost block and edit server_name appropriately (use a domain name instead of an IP address).
hello, I installed following these tutorials, but now my site http://198.199.112.161 with this 503 error. I’ve restart nginx and varnish, but not solved. What do you advise?
In order to allow post preview you’ll have to change the default.vcl to something like this…
backend default { .host = “127.0.0.1”; .port = “8080”; }
sub vcl_recv {
# Allow posts preview
if (req.url ~ "preview=true") {
return(pass);
}
# Drop cookies sent to Wordpress
if (!(req.url ~ "wp-(login|admin)")) {
unset req.http.cookie;
}
}
sub vcl_fetch {
# Drop cookies sent to client
if (!(req.url ~ "wp-(login|admin)")) {
unset beresp.http.set-cookie;
}
}
I installed mysql, php, nginx, varnish and wordpress on ubuntu 12.04 and being able to view the site with the IP address given by digital ocean. After updating the DNS entries with my domain registrar, I can view the Wordpress site, but have problems getting to the WP Admin page. I get redirected to mydomain.com:8080/wp-admin/ and get an unable to connect message in my web browser. I assume there is a config file or something that needs updated with my domain name on my server setup, but I am unsure what it is.
Thanks!
Finally a varnish config that works with WordPress! Still cant do a bulk update of plugins thought but I’m willing to take that hit.
When clicked on Customize, the theme preview doesn’t appear. Instead a message appears saying session is expired and shows login box. Here’s an image to show what it looks like: http://i.imgur.com/18QwXvi.jpg
Hi, seemed to get everything working and then took a snapshot. Upon reboot the nginx service won’t start and I get an Error 503 Service Unavailable message, Guru Meditation: XID: 1847591584. Not sure how to start nginx. Any help appreciated
@Ersan: Do you have the following config in your Varnish config files? https://p.kk7.me/nijexabeqe.nginx
@gary: What’s the output of this command? <pre>tail /var/log/nginx/error.log</pre>
Kamal, thank you for responding. I have restarted Nginx and made some progress but having errors. I have placed it here as a jpg (click to enlarge) http://37.139.14.30/hello-world/ http://37.139.14.30/hello-world/
Try clearing it and browsing to your domain again so we can know which of the errors it is:
<pre>cat /dev/null > /var/log/nginx/error.log</pre>
@Kamal, yes I do have that in my Varnish config, but I got around the problem by setting the phpmyadmin to work on another port which Varnish doesn’t listen to.
In order to get this set, I had to use
server { listen [::]80 ipv6only=on;
Therefore I cannot get the proxy_pass to work
I have tried proxy_pass http://127:0:0:1:8080 as well as :80
Both cause an [emerg] invalid port in upstream …
Any suggestions?
@layne.heiny: <pre>http://127:0:0:1</pre> should be <pre>http://127.0.0.1</pre>
Dots, not colons :]
I was playing around with this Nginx WordPres setup the other day. Select the droplet with the docker application and then import the script below from Github. :-) I had it up and running in a container on a port pretty easily, it seemed very fast. https://github.com/eugeneware/docker-wordpress-nginx
I have successfully executed your procedure. Very informative! Is there any need of wordpress varnish plugin after this? thanks in advance.
@aacharya.vaddey: It should work without installing any Wordpress plugins.
After the setup I was unable to preview posts and pages. Searching for a solution I found the following config for Varnish default.vcl. Instead of above code enter this:
[…] backend default { .host = “127.0.0.1”; .port = “8080”; }
sub vcl_recv { if ( !(req.url ~ “(wp-login|wp-admin|preview=true)”) ) { unset req.http.cookie; } }
sub vcl_fetch { if ( !(req.url ~ “(wp-login|wp-admin|preview=true)”) ) { unset beresp.http.set-cookie; } }
[…]
Finally, it works great for me !! How about… THANK YOU VERY MUCH DIGITAL OCEAN Before Varnish : page load 7.3s after : 2.42s Kabouuum Toda rabba
Thanks for the excellent article, you can install Nginx, PHP and MySQL with Postfix and phpMyAdmin using EasyEngine (https://github.com/rtCamp/easyengine). I have tried EasyEngine and it help me to get into shell.
Regarding Varnish, I read this link recently (http://rtcamp.com/tutorials/why-we-never-use-varnish-with-nginx/), so I think we don’t need to install another package to handle our static content.
Did you notice that the author of the article you cited states “<b>Disclaimer:</b> I never used Varnish.”? Kinda hard to take someone at their word when they’ve never even tried it.
Strange happenings here. On backend, i can navigate my WordPress dashboard no issues. One I go to the frontend/live-site, refuses to keep me logged-in no matter how many times I try. Any thoughts?
Update: Turned off 'Users must be registered and logged in to comment ’ in WordPress > Settings > Discussion and activated JetPack Comments. It’s a temporary work-around till I figure out how to keep registered users logged in on the front end.
@Nicholas: Hmm, seems like varnish isn’t passing the cookies properly. What’s the output of <pre>cat /etc/default/varnish | curl -F ‘sprunge=<-’ http://sprunge.us</pre>?
If installing Varnish on Ubuntu 12.04, do we still add the repo <code>deb http://repo.varnish-cache.org/ubuntu/ lucid varnish-3.0</code>? Or should we change the name <code>lucid</code> to <code>precise</code>?
@Pablo: You should set it to your distro’s codename:
<pre>lsb_release -sc</pre>
@Nicholas: My bad, the command was stripped out. Try this instead: <pre>cat /etc/default/varnish | curl -F ‘sprunge=<-’ http://sprunge.us</pre>
Hi.
After [sudo rm /etc/nginx/sites-enabled/default]
Should I add new symlink of ‘Wordpress’ to /etc/nginx/sites-enabled? Cos folder would be empty after delete default. [sudo ln -s /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/wordpress]
If you’re in trouble with upload large files in wordpress-admin panel (like me), try to do this: tail /var/log/nginx/error.log.
Probably there’s a line that show this: “client intended to send too large body”. So, it’s only do this: sudo nano /etc/nginx/nginx.conf
Add or modify the following line on http{…} client_max_body_size 20M;
That’s all folks :D.
hi kamal very nice article, I’m doing some research for my thesis about varnish, I want to know, what is pros and cons from using varnish for web cache server ? and what we can configure in varnish ? thx, sorry for my bad english,
@eko: I’ve never used Varnish myself, see if <a href=“http://en.wikipedia.org/wiki/Varnish_(software)”>http://en.wikipedia.org/wiki/Varnish_(software)</a> helps.
I’ve like to share my very succesful 5US droplet benchmark: LEMP, APC and varnish.
ANALYSIS This rush generated 21,625 successful hits in 57.78 seconds and we transferred 184.75 MB of data in and out of your app. The average hit rate of 374.28/second translates to about 32,338,133 hits/day. The average response time was 31 ms.
https://www.blitz.io/report/ad1a82454ca764fce66f361317eb8510#/
Got Varnish installed, but can’t find a way to flush/purge/ban the cache. Tried everything I’ve found on the internet and notthing i working. The only effective way is to reboot the droplet. Any ideas?
@Bruno: Try restarting Varnish – I believe that should clear the cache.
I’m used to have W3Total Cache and DB Cache realoaded fix plugins installed in my Wordpress site, at a shared hosting server.
After installing all os these and also Varnish, do you think i can still have those plugins?? Or will they be irrelevant due to Varnish?? Or even a conflict of caches?? (i’m a newbie is this part so it’s probally that i dont know much what i’m talking about xD)
Hi. Everything seems to work good on web, but I run into an error while trying to run varnishstat.
varnishstat: error while loading shared libraries: libvarnishapi.so.1: cannot open shared object file: No such file or directory
Can anyone please help me and fix it?
thanks in advance.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.