Magento 2.1 Varnish Cache not Purge

Finally I fixed myself the issue.

env.php

'http_cache_hosts' => 
 array (
 0 => 
   array (
  'host' => '127.0.0.1',
  'port' => '80',
  ),
),

default.vcl

if (req.method == "PURGE") {
if (client.ip !~ purge) {
    return (synth(405, "Method not allowed"));
}
if (!req.http.X-Magento-Tags-Pattern) {
    return (synth(400, "X-Magento-Tags-Pattern header required"));
}
ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);

# If all Tags should be purged clear
# ban everything to catch assets as well
if (req.http.X-Magento-Tags-Pattern == ".*") {
  ban("req.url ~ .*");
}

return (synth(200, "Purged"));
}

netstat -tulnp | grep varnish

see which port is actually used by Varnish service. i guess your settings to Varnish interface port is wrong.

Varnish by default is running admin on 127.0.0.1:6082 so obviously you send cache purge requests to nowhere...

check varnish.params you will see these:

# Default address and port to bind to. Blank address means all IPv4
# and IPv6 interfaces, otherwise specify a host name, an IPv4 dotted
# quad, or an IPv6 address in brackets.
VARNISH_LISTEN_ADDRESS=127.0.0.1
VARNISH_LISTEN_PORT=80

# Admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082

you need cache purge sent to 127.0.0.1:80 where is your varnish is listening.


Adding something really important to George George's answer:

Run: bin/magento config:set system/full_page_cache/caching_application 2 (otherwise the purge request won't be sent!)

Then: bin/magento setup:config:set --http-cache-hosts=127.0.0.1:6081

Then change default.vcl to add this:

if (req.method == "PURGE") {
    if (client.ip !~ purge) {
        return (synth(405, "Method not allowed"));
    }
    # To use the X-Pool header for purging varnish during automated deployments, make sure the X-Pool header
    # has been added to the response in your backend server config. This is used, for example, by the
    # capistrano-magento2 gem for purging old content from varnish during it's deploy routine.
    if (!req.http.X-Magento-Tags-Pattern && !req.http.X-Pool) {
        return (synth(400, "X-Magento-Tags-Pattern or X-Pool header required"));
    }
    if (req.http.X-Magento-Tags-Pattern) {
      ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);
    }
    if (req.http.X-Pool) {
      ban("obj.http.X-Pool ~ " + req.http.X-Pool);
    }

    ###
    ### THIS IS WHAT YOU MUST ADD
    ###

    # If all Tags should be purged clear
    # ban everything to catch assets as well
    if (req.http.X-Magento-Tags-Pattern == ".*") {
      ban("req.url ~ .*");
    }

    ###
    ### END OF THIS IS WHAT YOU MUST ADD
    ###

    return (synth(200, "Purged"));
}