How to Configure Varnish Cache With Apache on CentOS 7

Post Date: May 05, 2019
Last Updated: October 19, 2026

Introduction

Website performance is a critical factor in delivering a smooth user experience. Slow page loading, repeated requests to the web server, and inefficient handling of static content can increase server resource consumption and affect application responsiveness.

Varnish Cache is a high-performance HTTP reverse proxy that sits in front of a web server and caches eligible responses. By serving cached content directly, Varnish can reduce the number of requests reaching the backend server and improve response times.

Apache HTTP Server is widely used to host websites and web applications. Combining Apache with Varnish allows administrators to separate request handling from content processing. Varnish receives incoming HTTP requests, checks whether a suitable cached response exists, and forwards requests to Apache when the content needs to be retrieved from the backend.

In this guide, we will explain how to install and configure Varnish Cache with Apache on CentOS 7. You will learn how to configure the listening ports, define the Apache backend, start the services, verify HTTP responses, and troubleshoot common configuration issues.

This setup is useful for administrators managing websites, content management systems, and applications that can benefit from HTTP response caching.

Important: CentOS 7 reached end of life on June 30, 2024. This guide preserves the original CentOS 7 configuration approach for legacy environments. For new production deployments, use a currently supported Linux distribution and a compatible Varnish version.

What Is Varnish Cache?

Varnish Cache is an HTTP accelerator designed to improve the performance of web applications by caching HTTP responses.

It operates as a reverse proxy between clients and the backend web server.

When a client requests a page, Varnish checks whether it has a valid cached response. If the response is available, Varnish can return it without contacting Apache. Otherwise, Varnish forwards the request to Apache, receives the response, and may cache it according to the configured caching rules and HTTP headers.

Key Benefits of Varnish Cache

  • Faster response times: Serves eligible cached responses without repeatedly processing the same request in Apache.
  • Reduced backend workload: Decreases the number of requests that Apache must handle.
  • Improved scalability: Helps websites serve more requests when responses can be cached effectively.
  • Flexible caching rules: Allows administrators to control which requests and responses should be cached.
  • HTTP reverse proxy functionality: Routes requests between clients and backend servers.

Actual performance improvements depend on the application, cache hit ratio, server resources, network conditions, and caching configuration. No fixed performance multiplier is guaranteed.

Architecture: Varnish Cache and Apache

In this configuration, Varnish acts as the frontend HTTP reverse proxy, while Apache operates as the backend web server.

Varnish listens on port 80, and Apache listens on port 8080.

Request Flow

  1. A client sends an HTTP request to the server on port 80.
  2. Varnish receives the request.
  3. Varnish checks its cache for a suitable response.
  4. If a valid cached response exists, Varnish returns it to the client.
  5. If the response is not cached, Varnish forwards the request to Apache on port 8080.
  6. Apache processes the request and returns the response to Varnish.
  7. Varnish caches the response when permitted by its caching rules and the response headers.
  8. Varnish returns the response to the client.

Flow Map 1: Overall Architecture

Varnish Cache and Apache architecture diagram showing how HTTP requests flow from a web client to Varnish on port 80 and then to Apache on port 8080 on a cache miss. Varnish stores cacheable responses and returns cached or backend responses to the client.

Prerequisites

Before installing Varnish Cache, ensure that the following requirements are met.

  • A CentOS 7 server with administrative access.
  • Apache HTTP Server installed and working.
  • Root access or a user with sudo privileges.
  • Network access to the required package repositories.
  • Ports 80 and 8080 available for the intended services.
  • A website or application that Apache can serve.

Verify the Operating System

Run the following command:

cat /etc/centos-release

Check Apache Status

sudo systemctl status httpd

If Apache is not installed, install it using the following command, provided the required repositories remain available:

sudo yum install -y httpd

Enable and start Apache:

sudo systemctl enable httpd
sudo systemctl start httpd

Check the Apache version:

httpd -v

Note: CentOS 7 is no longer supported. Its standard repositories may no longer provide packages normally. Legacy systems may require archived repositories, which should be handled carefully because they do not provide ongoing security updates.

Step 1: Install the Required Repository

The original CentOS 7 installation procedure uses the Extra Packages for Enterprise Linux (EPEL) repository.

Install the EPEL release package:

sudo yum install -y epel-release

Update the package metadata:

sudo yum makecache

Verify that the repository is available:

yum repolist

Repository availability and package versions depend on the system’s repository configuration.

Step 2: Install Varnish Cache

Install Varnish using the package manager:

sudo yum install -y varnish

After installation, verify the available Varnish version:

sudo varnishd -V

The output identifies the installed Varnish version and build information.

Version compatibility: Varnish configuration syntax, service parameters, and package availability can vary by version. Review the documentation corresponding to the version installed on the server before applying configuration changes.

Step 3: Start and Enable Varnish

Start the Varnish service:

sudo systemctl start varnish

Enable the service at boot:

sudo systemctl enable varnish

Check the service status:

sudo systemctl status varnish

If the service does not start, inspect its logs:

sudo journalctl -u varnish -n 100 --no-pager

At this stage, Varnish should be installed. The next step is to configure it to receive public HTTP requests and communicate with Apache.

Step 4: Configure Varnish to Listen on Port 80

By default, the original CentOS 7 Varnish package commonly uses port 6081 for HTTP traffic.

For this configuration, Varnish must listen on port 80, while Apache will use port 8080.

Open the Varnish service parameter file:

sudo vi /etc/varnish/varnish.params

Locate the listening port parameter:

VARNISH_LISTEN_PORT=6081

Change it to:

VARNISH_LISTEN_PORT=80

If the file contains a separate listening address parameter, make sure it is configured appropriately for your environment.

Save the file.

Important Configuration Note

The exact service parameter file and startup options depend on the installed Varnish package. Some versions use a systemd service override or another configuration file rather than /etc/varnish/varnish.params.

Inspect the service definition if the expected parameter is missing:

sudo systemctl cat varnish

Use the configuration mechanism supported by the installed package rather than assuming every Varnish version uses the same startup parameters.

Step 5: Configure the Apache Backend in Varnish

Varnish needs to know where to retrieve content when a request cannot be served from its cache.

Open the Varnish VCL configuration file:

sudo vi /etc/varnish/default.vcl

Configure the backend as follows:

vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

This example uses VCL 4.0 syntax, which is appropriate for compatible legacy Varnish releases. Check the VCL version and syntax requirements of the installed release before using it.

Backend Configuration Explanation

  • backend default: Defines the backend server Varnish uses to retrieve content.
  • .host = "127.0.0.1": Specifies that Apache is running on the same server.
  • .port = "8080": Specifies the port on which Apache will listen.

If Apache runs on a separate server, change the backend address and port to match that server’s configuration.

Validate the Varnish Configuration

Before restarting Varnish, check the VCL syntax:

sudo varnishd -C -f /etc/varnish/default.vcl

The exact command and required options can vary by Varnish version. If the installed package requires additional parameters or uses a different VCL configuration path, use its documented validation procedure.

Correct any reported configuration errors before proceeding.

Step 6: Configure Apache to Listen on Port 8080

Apache commonly listens on port 80 by default.

Because Varnish will now handle incoming HTTP traffic on port 80, Apache must use port 8080 for the backend connection.

Open the Apache configuration file:

sudo vi /etc/httpd/conf/httpd.conf

Find the existing directive:

Listen 80

Change it to:

Listen 8080

Review Virtual Host Configuration

If your Apache configuration includes virtual hosts that explicitly listen on port 80, update them to use port 8080 where appropriate.

For example:

<VirtualHost *:8080>
    ServerName example.com
    DocumentRoot /var/www/html

    <Directory "/var/www/html">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Replace example.com with your actual hostname.

Review any additional Apache configuration files under:

/etc/httpd/conf.d/

Check for conflicting port directives:

sudo grep -RniE '^[[:space:]]*Listen[[:space:]]|<VirtualHost' \
    /etc/httpd/conf /etc/httpd/conf.d

Avoid changing unrelated SSL virtual hosts unless you have planned and configured their corresponding ports and proxy paths.

Test Apache Configuration

Run:

sudo apachectl configtest

Expected output:

Syntax OK

If Apache reports an error, correct it before restarting the service.

Step 7: Restart Apache and Varnish

After updating both configurations, restart Apache first:

sudo systemctl restart httpd

Check Apache:

sudo systemctl status httpd

Then restart Varnish:

sudo systemctl restart varnish

Check Varnish:

sudo systemctl status varnish

If either service fails, inspect its logs before proceeding.

Apache logs:

sudo journalctl -u httpd -n 100 --no-pager

Varnish logs:

sudo journalctl -u varnish -n 100 --no-pager

Flow Map 2: Installation and Configuration Workflow

Step 8: Verify Listening Ports

Check whether Varnish and Apache are listening on their expected ports.

Run:

sudo ss -lntp | grep -E ':(80|8080|6081)\b'

The expected configuration is:

ServiceExpected PortPurpose
Varnish80Receives incoming HTTP requests
Apache8080Processes backend requests
Varnish default alternative port6081Should not be the active public HTTP listener in this setup

The output should show Varnish listening on port 80 and Apache listening on port 8080.

The precise process names and output formatting may differ by package version.

If another service already occupies port 80, Varnish may fail to start. Identify the conflicting process before making changes.

Step 9: Test the Apache Backend Directly

Before testing Varnish, verify that Apache responds on port 8080.

Run:

curl -I http://127.0.0.1:8080/

If Apache is configured correctly, it should return an HTTP response.

For a successful request, you may see:

HTTP/1.1 200 OK

The exact headers depend on your Apache configuration and website.

If the request fails, investigate Apache’s listening port, virtual host configuration, document root, application status, and logs.

Step 10: Test the Varnish Frontend

Once Apache is working on port 8080, test the Varnish frontend.

Run:

curl -I http://127.0.0.1/

For a website configured to return a successful response, you should see an HTTP status such as:

HTTP/1.1 200 OK

A response may include headers similar to these:

HTTP/1.1 200 OK
Date: ...
Server: Apache
X-Varnish: ...
Age: 0
Via: 1.1 varnish
Content-Type: text/html; charset=UTF-8

This is an illustrative example, not a guaranteed output.

The presence, order, and values of response headers depend on the Varnish version, VCL configuration, backend response, and header handling.

What Do the Headers Mean?

  • HTTP status: Indicates whether the request succeeded or encountered an error.
  • X-Varnish: May contain identifiers associated with Varnish request processing.
  • Age: When present, indicates the approximate age in seconds of a cached response.
  • Via: May identify an HTTP intermediary.
  • Server: May identify the backend server or another component, depending on header configuration.

The X-Varnish and Via headers alone do not prove that a response was served from the cache. Likewise, an Age value of 0 does not establish that caching is broken.

Step 11: Verify Cache Behavior

A successful HTTP response confirms that the request completed, but it does not necessarily mean that Varnish is caching the content.

To inspect Varnish activity, use the tools available in your installed version.

For example:

sudo varnishstat

Look at counters associated with client requests, cache hits, and cache misses.

Common counter names in compatible Varnish releases include:

MAIN.cache_hit
MAIN.cache_miss
MAIN.client_req

Counter names and availability vary between releases.

Make several requests to a cacheable page:

curl -I http://127.0.0.1/
curl -I http://127.0.0.1/
curl -I http://127.0.0.1/

Observe the cache-related counters before and after the requests.

Flow Map 3: HTTP Request and Cache Decision

Varnish Cache with Apache configuration showing the HTTP request flow between Varnish and Apache

Important: A cache miss does not automatically mean the response will be stored. Varnish may bypass caching or decline to cache a response because of its VCL rules, cookies, authorization headers, cache-control directives, or other conditions.

Step 12: Configure Firewall Access

If the server uses firewalld, allow HTTP traffic on port 80.

Check the firewall status:

sudo firewall-cmd --state

If firewalld is active, add the HTTP service:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload

Verify the rule:

sudo firewall-cmd --list-services

In this design, port 8080 should normally remain inaccessible to public clients because it is the backend port.

If Apache and Varnish run on the same server, keep Apache’s backend listener restricted to the intended interfaces where possible. A loopback-only listener can be used if the deployment supports it.

For a remote backend, permit access to port 8080 only from the Varnish server or other explicitly authorized systems.

Troubleshooting Common Issues

1. Varnish Fails to Start

Check the service status:

sudo systemctl status varnish

Review recent logs:

sudo journalctl -u varnish -n 100 --no-pager

Possible causes:

  • Invalid VCL syntax.
  • Incorrect service startup parameters.
  • Another service already listening on port 80.
  • Unsupported configuration directives.
  • Permission or runtime directory problems.

Validate the configuration and inspect the service definition before restarting.

2. Apache Fails to Start

Run:

sudo apachectl configtest
sudo systemctl status httpd

Check the logs:

sudo journalctl -u httpd -n 100 --no-pager

Possible causes:

  • Incorrect virtual host ports.
  • Duplicate Listen directives.
  • Syntax errors in Apache configuration files.
  • Port conflicts.
  • Incorrect file permissions.

Ensure Apache uses the intended backend port and that all virtual hosts are consistent with the new configuration.

3. Varnish Returns HTTP 503

A 503 Service Unavailable response can occur when Varnish cannot successfully communicate with its backend.

Test Apache directly:

curl -I http://127.0.0.1:8080/

Inspect the backend definition:

sudo cat /etc/varnish/default.vcl

Confirm that Apache is running and listening on the configured backend address and port.

Also check Varnish logs for connection errors and backend health problems.

4. Website Loads, but Cache Hits Do Not Increase

A working website does not necessarily mean that its responses are cacheable.

Check Varnish statistics:

sudo varnishstat

Review the VCL configuration and response headers.

Potential causes include:

  • The response contains Cache-Control: no-cache or Cache-Control: private.
  • The response sets cookies that affect caching behavior.
  • The request contains an authorization header.
  • The VCL explicitly passes the request to Apache.
  • The response is not cacheable under the configured rules.
  • The application generates unique or dynamic responses.

Do not force caching for authenticated or personalized content without understanding the security implications.

5. Apache Is Still Listening on Port 80

Inspect the configuration:

sudo grep -RniE '^[[:space:]]*Listen[[:space:]]|<VirtualHost' \
    /etc/httpd/conf /etc/httpd/conf.d

Check the active listeners:

sudo ss -lntp | grep -E ':(80|8080)\b'

Update any conflicting Apache configuration files and restart Apache after validating the configuration.

6. SELinux Prevents Apache from Using Port 8080

On SELinux-enabled CentOS 7 systems, custom HTTP ports may require additional policy configuration.

Check the SELinux mode:

getenforce

Inspect the permitted HTTP ports:

sudo semanage port -l | grep http_port_t

If port 8080 is not permitted for the relevant HTTP service, configure the appropriate SELinux policy using the supported administrative tools.

For example, where the port is not already assigned to another type:

sudo semanage port -a -t http_port_t -p tcp 8080

If the port is already defined under another type, review the existing assignment before making a modification.

The semanage command may require the appropriate policy management package.

Do not disable SELinux as a shortcut for resolving configuration problems.

Security and Production Recommendations

Before deploying this architecture in production, consider the following practices:

  1. Use a supported operating system: CentOS 7 no longer receives normal security maintenance. Plan a migration to a supported distribution.
  2. Keep the backend private: Restrict access to Apache’s backend port so clients cannot bypass Varnish unintentionally.
  3. Protect personalized content: Carefully evaluate caching rules for login pages, dashboards, shopping carts, and user-specific responses.
  4. Use HTTPS appropriately: Configure TLS termination at Varnish or an upstream proxy/load balancer according to your architecture. Plain HTTP on port 80 does not provide encryption.
  5. Monitor cache performance: Track hit ratio, request rate, backend errors, memory usage, and response times.
  6. Validate configuration changes: Test VCL and Apache configuration before applying changes to production.
  7. Maintain a rollback plan: Back up configuration files and document how to restore the previous ports and service configuration.

Back Up the Configuration Files

Before modifying the configuration, create backups:

sudo cp -a /etc/varnish/default.vcl \
    /etc/varnish/default.vcl.backup

sudo cp -a /etc/httpd/conf/httpd.conf \
    /etc/httpd/conf/httpd.conf.backup

If the Varnish parameter file exists:

sudo cp -a /etc/varnish/varnish.params \
    /etc/varnish/varnish.params.backup

Keep backups in a location protected from unauthorized access and include them in your configuration management process.

Conclusion

Configuring Varnish Cache in front of Apache is an effective way to introduce HTTP response caching into a web hosting environment. With Varnish listening on port 80 and Apache serving requests on port 8080, incoming HTTP traffic can pass through the cache before reaching the backend web server.

In this guide, we covered installing Varnish, configuring the backend, changing Apache’s listening port, validating the configuration, testing HTTP responses, inspecting cache activity, and troubleshooting common service and connectivity issues.

The most important point is that a successful HTTP response does not automatically mean that caching is working. Administrators should also verify cache statistics, response headers, backend health, and the application’s caching behavior.

For production deployments, use appropriate cache rules, protect personalized content, monitor performance, and maintain a clear rollback procedure. Because CentOS 7 is no longer supported, migrating to a supported operating system should also be a priority for legacy environments.

When configured and monitored correctly, Varnish Cache and Apache can work together to reduce backend load and improve web application responsiveness.

Frequently Asked Questions (FAQ)

1. What is Varnish Cache?

Varnish Cache is an HTTP reverse proxy that can cache eligible responses and serve them to clients without repeatedly contacting the backend web server.

2. Why use Varnish with Apache?

Varnish can reduce Apache’s workload by serving cached responses directly. This can improve response times and help applications handle higher request volumes.

3. Which port does Varnish use in this configuration?

Varnish listens on port 80, which receives incoming HTTP requests from clients.

How to Modify the Apache VirtualHost Configuration for a Single Domain in cPanel

How to Configure a Custom VirtualHost in cPanel with Apache 2.4

Need Help with Apache Virtual Hosts in Ubuntu?

Need help with Apache Virtual Hosts in Ubuntu, domain configuration, website hosting, or Apache server management? Our experts can help with Apache configuration, Linux server administration, web server optimization, security hardening, and cloud hosting solutions. Get in touch with our team here.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Comment

Scroll to Top