Mostafa Mostafa - 1 year ago 46
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


echo "Switching between Apache and Varnish cache"

if grep -Fxq "apache_port=" /var/cpanel/cpanel.config
sed -i '/apache_port/c\apache_port=' /var/cpanel/cpanel.config
sed -i '/apache_port/c\apache_port=' /var/cpanel/cpanel.config

/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 Source

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 and apache on 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


  • 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.


  • 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. :)