【问题标题】:restarting httpd service in bash script not working在 bash 脚本中重新启动 httpd 服务不起作用
【发布时间】:2016-08-10 05:14:57
【问题描述】:

我创建了一个 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"

我不知道为什么重启 oof httpd 不能正常工作

【问题讨论】:

  • 不使用sudo 可以重启httpd 吗?
  • 这可能会有所帮助:How to debug a bash script?
  • @Cyrus 我正在使用另一个在线工具来调试脚本的语法
  • 您是否验证了/sbin/service httpd restart 在以root 身份登录时可以正常工作?

标签: bash apache centos varnish


【解决方案1】:

改用iptables端口重定向怎么样?

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

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

将流量切换到 apache(假设我们已经将它定向到 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.

将其切换回清漆:

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 的原因。如果你需要的话,你可以单独驱逐清漆。 :)

【讨论】:

  • 很棒的解决方案,非常感谢您的支持,但我实际上害怕使用任何我不理解的代码,所以请为我解释这两行:)
  • 也谢谢你。好吧,我根本不是 iptables 大师,但让我将其添加到答案中。
  • 非常感谢您的解释:)
  • 但是“&&”之后第一行的最后一个“\”呢?
  • 这是命令的常见外壳链接和转义行拆分。 cmd1 && cmd2 首先执行 cmd1,并且只有在成功完成时 cmd2 在第二位执行。如果cmd1 失败,则根本不会执行cmd2。您可以将其视为一种交易。反斜杠 (\) 允许您将较长的命令行拆分为更多行。仅此而已,就这么简单。
猜你喜欢
  • 2017-08-17
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2020-01-01
  • 2013-12-12
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多