We are running node application in Azure Virtual Machine, meanwhile we also want to restart VM at some certain time with the help of Azure Automation (or via management portal).
But how can we restart the node application after VM restarted?
We tried a lot of ways to achieve this, including add the Task Scheduler, add command to the registry key (LocalMachine\..\Run
), use Custom Script Extension for VM ...
All above failed. What we want is after the VM restart, the node application can be started automatically. If we then remote to the VM with predefined account, some of above ways can work. However, this is not the scenery, we only want to remote only once at the beginning, not every restart.
So, what't the right way to achieve this, to start a process or execute a command after VM automatically restart without manually login?
I've already tried a lot of ways to achieve this goal, and from my point of view, Task Scheduler is the best choice to do this kind of job.
The key point is never let the Windows Command Prompt exist after starting your process. For example, at first we use forever to launch node application. Since the forever command returns quickly, which means all the command execution finished. Thus, the Windows Command Prompt process will be killed, and along with the node process.
What we did is, we use another way to launch forever (forever-monitor), which is used in the code. By doing this, we can simply use node
command to start this forever startup file. Since the node
command will block the command prompt, the node application won't be killed anymore.
Another alternative is use Azure Automation remotely run the startup script.
The full script can be found here, key point is:
$PSCommandResult = Invoke-command -AsJob -ConnectionUri $Using:Uri.AbsoluteUri -credential $Using:mycreds -ScriptBlock { Invoke-Expression "D:\start.ps1" }
In start.ps1
script, we also should not exit the execution, which we can use Start-Sleep
command to achieve this. The script can be:
forever start --sourceDir D: start.js
Start-Sleep -s 86400
Hope this two approaches can help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With