How to Install Varnish with Apache on Ubuntu

Varnish is an amazing frontend cache that is useful for serving static pages and reducing load on your server. In periods of high server activity and traffic, Varnish can be a life saver. Also, Varnish is extremely fast and effective at reducing your page load times, which helps with your SERPs and improves user experience.

1. Add the Varnish Repository

Varnish can be installed by adding the Varnish repository to your sources and using apt-get to install it.

To add the repository, run the following command:

2. Edit List of apt Sources

Open the /etc/apt/sources.list in your favorite text editor so we can add the Varnish repository.

Next, add the Varnish repository at the end of the file.

Save your work and exit out to the command line.

3.  Install Varnish

Use the usual apt-get to install Varnish.

4. Configure Varnish DAEMON_OPTS

Now it is time to configure Varnish. This process will vary depending upon your CMS and/or framework and how your site is set up, but we will get you started with a basic configuration.

Open the /etc/default/varnish file:

Look for “alternative 2” and uncomment the following code. Change the ports as necessary.

Basically, we are setting Varnish to use Port 80, using /etc/varnish/default.vcl as our configuration file, and allocating 256MB of memory.

5. Varnish VCL Configuration

The VCL file in Varnish is extremely important and allows for very specific configurations indicating which pages to cache, how to treat cookies, what to do about different user-agents, and so on.

The basics will be covered here, but you will need to look closely at the VCL file in the future to get optimal performance. Don’t worry because it’s straightforward and you can do it!

Open the VCL file:

Now we have to tell Varnish where to grab content for your site. Here we are using the same server and we will set up Apache on port 8888.

Save and exit the file.

6. Change the Apache Ports

By default, Apache is configured to run on Port 80. We will change the port to be 8888.

Open the Apache ports file:

Now look for the NameVirtualHost and Listen lines and change them to Port 8888.

7. In the Virtual Host, Change the Port to 8888

In the settings for your virtual host, you will need to tell Apache to look on Port 8888.

Now change the port:

Save and exit the file.

8. Restart Apache and Varnish

9. Watch in Amazement at the Details of your Varnish Server Running

You can check in on Varnish with its built-in stats readout.

You are done! That was easy wasn’t it? Now you are well on your way to having a fast and efficient server configuration.

Ryan Frankel

Questions or Comments? Ask Ryan!

Ask a question and Ryan will respond to you. We strive to provide the best advice on the net and we are here to help you in any way we can.