Mostafa Mostafa - 3 months ago 16
Apache Configuration Question

restarting httpd service in bash script not working

I created a bash script to switch between using Apache and Varnish

But the commands of restarting the httpd service not working RECENTLY

the script was working fine before months

#!/bin/bash

echo "Switching between Apache and Varnish cache"

if grep -Fxq "apache_port=0.0.0.0:80" /var/cpanel/cpanel.config
then
sed -i '/apache_port/c\apache_port=0.0.0.0:8080' /var/cpanel/cpanel.config
else
sed -i '/apache_port/c\apache_port=0.0.0.0:80' /var/cpanel/cpanel.config
fi

/usr/local/cpanel/whostmgr/bin/whostmgr2 –updatetweaksettings &&
/scripts/rebuildhttpdconf &&
service httpd restart &&
service varnish restart &&

echo "Done"


I don't know Why the restarting oof httpd is not working exactly

Answer

What about to use iptables port redirection instead?

Basically, you have your varnish and apache running on their own unprivileged ports concurrently and redirect all traffic to port 80 to varnish or apache on kernel level.

Let run varnish on 0.0.0.0:6081 and apache on 0.0.0.0:8080 and play with these 2 command sets (under root or sudo):

To switch traffic to apache (assuming we have already it directed to varnish):

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080 && \
iptables -t nat -D PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 6081
# first command adds rule to redirect all traffic on interface eth0 (adjust as needed) from port 80 to port 8080, rule is added to the end of rules list, so already active rule redirecting traffic to 6081 is still in charge with higher priority
# second line deletes rule redirecting traffic from port 80 to port 6081, to new rule can come into effect. moreover, it's executed only if previous command (-A) was finished successfully.

To switch it back to varnish:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 6081
iptables -t nat -D PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
# inverted rules from above, adds redirection to 6081 and removes redirection to 8080 if addition was successful

Pros:

  • No varnish restarts, so no cold cache.
  • No port 80 outage overall if you first add the new redirection rule and then delete still valid older one.
  • Much safer, if addition of the first rule fails, skip deleting still valid rule and report problem. You are still running as before failed attempt. Just play with scripts as needed.

Cons:

  • No cache eviction as there is no varnish restart. But I guess this is not the reason you try to switch traffic to apache. And you can evict varnish separately if you need afterall. :)