在bash脚本中重启httpd服务无法正常工作

时间:2016-08-06 03:30:09

标签: bash apache centos varnish

我创建了一个bash脚本,用于在使用Apache和Varnish之间切换

但重启httpd服务的命令最近不能正常工作

脚本在几个月前工作正常

#!/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"

我不知道为什么重新启动的httpd无法正常工作

1 个答案:

答案 0 :(得分:1)

如何使用 iptables 端口重定向呢?

基本上,您同时在自己的非特权端口上运行varnish和apache,并在内核级别将所有流量重定向到端口80到varnish或apache。

让我们在 0.0.0.0:6081 上运行varnish,在 0.0.0.0:8080 上运行apache并使用这两个命令集(在root或sudo下):

要将流量切换到apache(假设我们已将其定向到清漆):

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.

将其切换回清漆:

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

优点:

  • 没有清漆重启,所以没有冷缓存。
  • 如果您首先添加新的重定向规则,然后删除仍然有效的旧重定向规则,则不会导致整个端口80中断。
  • 更安全,如果添加第一条规则失败,请跳过删除仍然有效的规则和报告问题。您仍然在尝试失败之前仍在运行。只需根据需要使用脚本。

缺点:

  • 没有缓存驱逐,因为没有清除重启。但我想这不是你尝试将流量切换到apache的原因。如果你需要,你可以单独驱逐清漆。 :)