Debian – how to make varnish listen on several ports

debianPROXYreverse-proxyvarnish

I have multiple virtual machines with two services on two different ports on each of them. I want to access to these service with url like http://virtual_url_1:80 and http://virtual_url1:8080 for the one installed on the first VM, and so on.

I am using varnish to relay the traffic from the hardware node to the virtual nodes. I can distinguish virtual_url_1 from virtual_url_2 for instance with this:

if (req.http.host == "virtual_url_1") {
    set req.backend = virtual_node_1;
    remove req.http.X-Forwarded-For;
    set req.http.X-Forwarded-For = client.ip;
    if (req.request == "POST") {
        return(pipe);
    }   
    return (lookup);
}

For the distinction on the port, I have seen that varnish can listen on different ports with this on /etc/default/varnish

DAEMON_OPTS="-a 0.0.0.0:80,0.0.0.0:8080 \
   -T localhost:6082 \
   -f /etc/varnish/default.vcl \
   -S /etc/varnish/secret \
   -s file,/var/lib/varnish/$INSTANCE/varnish_storage.bin,1G"

But now, once intercepted, the problem is to relay the traffic from port 80 to backend 80 and the one from port 8080 to backend 8080.

There is a req.http.host variable, i am looking for a req.port like one to perform this purpose.

Could anyone provide me with some piece of advice? Is it even possible? Or should I run two different instances of varnish (the first one listening and replying on port 80, the second one on port 8080), which I prefer avoid?

Many thanks!

Best Answer

Use the server.port Variable in your vcl and it should do the trick.
You shouldn't have to run two instances of varnish!
See man 7 vcl for more variables and information about them.