启动 Vagrant VM 并通过 shell 脚本启动 Node.js 脚本

Start Vagrant VM and start Node.js script by shell script

我在 Vagrant 上安装了 StackEdit。我想一键启动 Vagrant 和 StackEdit。 我创建了 bash 脚本:

#!/bin/bash

vagrant up

#ssh -p 2222 -i /d/stackedit/.vagrant/machines/default/virtualbox/private_key vagrant@127.0.0.1 -t '/home/vagrant/Code/start_server.sh'

start "C:\Program Files\Mozilla Firefox\firefox.exe" http://stackedit.app:5000

start_server.sh 在 VM

if [ $(ps -e|grep node|wc -l) = "0" ] ; then
    (export PORT=5000 && node Code/Project/public/stackedit/server.js) &
fi
sleep 5

exit 0

如果我 运行 start_server.sh 通过 ssh 手动一切正常,但是当我在启动脚本中使用 ssh 尝试它时 - 现在注释行 - 服务器没有 运行.

我尝试将此脚本复制到 /ect/rc.local,但结果是一样的。 我也尝试将 @reboot /home/vagrant/Code/start_server.sh 添加到 crontab -e,但没有成功。

谁能帮帮我?

我的系统是Windows10.我用GitBash.

你应该把所有东西都放在你的 Vagrantfile

#运行 配置

您可以使用 shell provisioner

从 Vagrantfile 运行 您的脚本
Vagrant.configure("2") do |config|
  config.vm.provision "shell", path: "Code/start_server.sh"
end

检查,你有一些选项默认情况下它会 运行 作为 root 所以你可以改变如果你想 运行 你的脚本作为 vagrant 用户

Vagrant.configure("2") do |config|
  config.vm.provision "shell", path: "Code/start_server.sh", privileged: false
end

并且您还可以确保每次启动 VM 时都运行您的脚本(默认情况下它 运行 仅一次或在特定调用 provision 参数时)

Vagrant.configure("2") do |config|
  config.vm.provision "shell", path: "Code/start_server.sh", run: "always"
end

#系统运行ning

后打开网站

Vagrantfile 是一个 ruby 脚本,因此您可以从文件中调用任何命令,但它会在任何情况下立即 运行 命令。

然后,如果你想在盒子启动后运行,你可以使用vagrant trigger并做类似

的事情
Vagrant.configure(2) do |config|
  .....
  config.trigger.after :up do |trigger|
    trigger.run = {inline: 'system("open", "http://stackedit.app:5000"')
  end
end