开始&停止Nginx,mysql服务器

时间:2011-11-24 21:54:33

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我正在开发 Rails v2.3 应用。在 Ubuntu 计算机上使用 MySQL v5.1 数据库。

我知道要启动的命令,在命令行上停止 Nginx MySQL

但是现在,我需要在我的Rails应用程序的 rake任务之一中定义以下过程:

stop Nginx --> stop(shut down) MySQL --> ... --> start MySQL --> start Nginx

这意味着所有这些都需要在我的 Rails 应用的 rake任务中的ruby脚本中定义。

我不确定如何在我的 rake任务中运行ruby代码运行上述过程(执行命令)?

3 个答案:

答案 0 :(得分:1)

查看Ruby's Kernel module(内置)。使用反引号,您可以运行命令来停止/启动nginx和MySQL,甚至检查它们的退出代码以确保它们正确执行(如果您的停止/启动脚本支持退出代码)。

示例:

# In your Rakefile
namespace :servers do
  task :stop do
    nginx_stop_output = `service nginx stop`
    if $?.exitstatus != 0
      # handle shutdown failure
    end

    mysql_stop_output = `service mysql stop`
    if $?.exitstatus != 0
      # handle shutdown failure
    end
  end

  task :start do
    nginx_start_output = `service nginx start`
    if $?.exitstatus != 0
      # handle startup failure
    end

    mysql_start_output = `service mysql start`
    if $?.exitstatus != 0
      # handle startup failure
    end
  end
end

在反引号中替换你自己的停止/启动命令。

然后,您可以使用rake servers:stoprake servers:start运行这些任务。

答案 1 :(得分:0)

除非nginx不在端口80上运行,否则你可能使用sudo。在这种情况下,您的选择是:

  1. 修改/etc/sudoers以允许您的用户使用nginx而不会被要求输入密码。

  2. 使用Open3#popen3代替``或system()来运行shell命令。 Open3允许您在命令提示您输入其他信息时与命令进行交互,因此您可以在rake任务尝试执行命令时输入sudo密码。

答案 2 :(得分:0)

使用gem systemu执行命令。它比任何内置的Ruby命令行设施都要好。为了处理您的服务器环境,您可能会考虑像vlad这样的部署框架。