- Автоматический перезапуск приложений Node.js с помощью nodemon
- Требования
- 1: Установка nodemon
- Глобальная установка nodemon
- Локальная установка nodemon
- 2: Создание простого проекта Express с помощью nodemon
- 3: Параметры nodemon
- 4: Конфигурация nodemon
- Заключение
- Кто как реализует автозапуск приложений node.js?
- How to restart node app from iteself? #923
- Comments
- ronovar commented Oct 25, 2017 •
- Knighton910 commented Oct 26, 2017
- ronovar commented Oct 26, 2017
- GithubGoldMiner commented Oct 27, 2017
- ORESoftware commented Oct 27, 2017 •
- ronovar commented Oct 28, 2017
- gireeshpunathil commented Mar 26, 2018
- gireeshpunathil commented Mar 27, 2018
- rockyjvec commented Sep 24, 2018
- twome commented Mar 27, 2019 •
- The NodeSource Blog
- All Posts
- How To
- Running Your Node.js App With Systemd — Part 1
- What is systemd Anyway?
- Running our App Manually
- Creating a systemd Service File
- Using systemctl To Control Our App
- Wrapping Up
Автоматический перезапуск приложений Node.js с помощью nodemon
В Node.js нужно перезапускать процесс, чтобы обновления вступили в силу – а это дополнительный шаг в разработке. К счастью, его можно автоматизировать с помощью nodemon.
nodemon – это утилита интерфейса командной строки (CLI), разработанная @rem, которая отслеживает файловую систему приложения Node и автоматически перезапускает процесс, если есть такая необходимость.
В этом мануале вы научитесь устанавливать и настраивать nodemon.
Требования
Чтобы выполнить этот мануал, вам понадобится локальная установка Node.js. Чтобы получить такую, следуйте нашим инструкциям по установке Node.js и созданию локальной среды разработки:
Примечание: Больше мануалов по работе с Node.js вы найдете здесь.
1: Установка nodemon
Для начала нам нужно установить утилиту nodemon на свой компьютер. Установите ее глобально или локально с помощью npm или Yarn.
Глобальная установка nodemon
Чтобы установить nodemon глобально с помощью npm, введите:
npm install nodemon -g
Чтобы сделать это с помощью Yarn, введите:
yarn global add nodemon
Локальная установка nodemon
Вы можете установить nodemon локально (утилита будет доступна только в рамках вашего проекта, а не во всей системе). Утилиту nodemon можно установить как dev зависимость с помощью флага –save-dev (или –dev):
npm install nodemon —save-dev
Это можно сделать и с помощью Yarn:
yarn add nodemon —dev
Устанавливая nodemon локально, вы должны понимать, что не сможете использовать ее из командной строки.
command not found: nodemon
Однако вы сможете использовать утилиту как часть скриптов npm или запускать ее с помощью npx.
2: Создание простого проекта Express с помощью nodemon
Утилиту nodemon можно использовать для запуска скрипта Node. Например, если в файле server.js у вас есть конфигурация сервера Express, мы можем запустить его и проследить за изменениями с помощью команды:
Вы можете передавать команде аргументы (они передаются так же, как скриптам, запущенным с помощью Node):
nodemon server.js 3006
Каждый раз, когда вы вносите изменения в файл с одним из наблюдаемых по умолчанию расширений (это файлы .js, .mjs, .json, .coffee и .litcoffee) в текущем каталоге или подкаталоге, процесс перезапускается.
Предположим, мы записываем тестовый файл server.js, который выводит такое сообщение:
Dolphin app listening on port $
Мы можем запустить его с помощью утилиты nodemon:
И мы увидим следующий вывод в терминале:
[nodemon] 1.17.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Dolphin app listening on port 3000!
Пока nodemon работает, давайте внесем изменения в файл server.js. Для примера попробуйте отредактировать сообщение:
Shark app listening on port $
Мы получим дополнительный вывод:
[nodemon] restarting due to changes.
[nodemon] starting `node server.js`
Shark app listening on port 3000!
Вывод приложения Node.js отображается должным образом. Вы можете перезапустить процесс в любое время, набрав rs и нажав Enter.
Также nodemon будет искать файл main, указанный в файле package.json вашего проекта:
Или скрипт start:
После внесения изменений в package.json вы можете вызвать nodemon, чтобы запустить пример приложения в режиме просмотра без необходимости передавать server.js.
3: Параметры nodemon
Вы можете изменить параметры конфигурации nodemon.
Давайте рассмотрим несколько основных опций:
- –exec: позволяет указать двоичный файл, с помощью которого будет выполняться файл. Например, в сочетании с двоичным файлом ts-node –exec может отслеживать изменения и запускать файлы TypeScript.
- –ext: указывает разные расширения отслеживаемых файлов. Эта опция принимает список расширений, разделенных запятыми (например, –ext js, ts).
- –delay: по умолчанию nodemon ждет одну секунду, чтобы перезапустить процесс при изменении файла, но с помощью опции –delay вы можете указать другую продолжительность ожидания. Например, nodemon –delay 3.2 установит задержку в 3,2 секунды.
- –watch: позволяет указать несколько отслеживаемых каталогов или файлов. Добавьте параметр –watch для каждого каталога, который вы хотите отслеживать. По умолчанию утилита отслеживает текущий каталог и его подкаталоги, а с помощью –watch вы можете сузить диапазон до определенных подкаталогов или файлов.
- –ignore: позволяет игнорировать определенные файлы, шаблоны файлов или каталоги.
- –verbose: выдает более подробный вывод с информацией о том, какие файлы были изменены и стали причиной перезапуска.
Вы можете просмотреть все доступные параметры с помощью следующей команды:
Давайте с помощью этих параметров создадим команду, которая:
- Отслеживает каталог server
- Задает файлы с расширением .ts
- Игнорирует файлы с суффиксом .test.ts
- Выполняет файл (server/server.ts) с помощью ts-node
- Ожидает перезапуска в течение трех секунд после изменения файла
nodemon —watch server —ext ts —exec ts-node —ignore ‘*.test.ts’ —delay 3 server/server.ts
Эта команда включает параметры –watch, –ext, –exec, –ignore и –delay, чтобы соответствовать условиям нашего сценария.
4: Конфигурация nodemon
Как видно из предыдущей команды, добавление флагов nodemon может оказаться довольно утомительным процессом. Лучшее решение для проектов, которым требуются определенные конфигурации, – указать эти конфигурации в файле nodemon.json.
Например, вот те же конфигурации, что и в предыдущей команде – только теперь они помещены в файл nodemon.json:
Обратите внимание: вместо флага –exec мы используем здесь execMap. execMap позволяет указывать двоичные файлы, которые следует применять при определенных расширениях файлов.
Если вы не хотите добавлять конфигурационный файл nodemon.json в свой проект, вы можете добавить эти конфигурации в файл package.json с помощью ключа nodemonConfig:
После внесения изменений в nodemon.json или package.json вы можете запустить утилиту nodemon с необходимым скриптом:
nodemon подберет конфигурации из файла и использует их. Таким образом, ваши конфигурации можно сохранять, публиковать и повторять, чтобы избежать ошибок и необходимости вручную вводить опции (или постоянно копировать и вставлять их).
Заключение
Теперь вы знаете, как использовать nodemon с вашими приложениями Node.js. Этот инструмент помогает автоматизировать процесс остановки и запуска сервера Node.
За дополнительной информацией о доступных функциях и устранении ошибок обратитесь к официальной документации.
Источник
Кто как реализует автозапуск приложений node.js?
Через systemd очень легко это делается.
В начале создаём файл сервиса нашего node приложения по следующему типу:
После чего делаем следующие действия в консоли:
Всё — так это делается на линукс системах, а как на винде не знаю, там свои заморочки =))
Ну и надо чтобы systemd был установлен в системе, на убунте он вроде доступен(есть) с версии 14.10
Плюсы по сравнению с forever
умеет садиться в автозапуск *nix систем при том использует все существующие сегодня варианты (при наличии system.d добавится в него, иначе в зависимости от ОС, например в убунту без system.d садиться в init.d)
Делается это одной командой: pm2 startup
Умеет следить за памятью и нагрузкой на процессор, что удобно, когда нет времени искать утечку памяти, а приложение должно работать, так же позволяет это все мониторить в реальном времени
Ротация логов. Перехватывает stdout и stderr, пишет логи в файл, дает возможность подключится к выводу приложения в реальном времени
Умеет запускать приложения с помощью других интерпретаторов, а так же просто бинарники
Приложения на node умеет запускать в кластере
Источник
How to restart node app from iteself? #923
Comments
ronovar commented Oct 25, 2017 •
I need when i call api for /restart to restart application.js i try using this code:
But the problem is that node is killed but application.js is not run and application is not running.
I read that i need to use spawn not child_process.exec but i im unable to make it work. so can you please post me above code of using spawn?
I im using node version: v7.10.1
ubuntu server x64 14.04 LTS
I need to kill node (application.js) and run it again. so short say restart application.js
The text was updated successfully, but these errors were encountered:
Knighton910 commented Oct 26, 2017
ronovar commented Oct 26, 2017
I need to restart it internaly from itself. i have app with buttons restart stop and shutdown. so when user click stop if i use nodemon it will restart not kill app. so do you have idea how can i use to restart internally using javascript code?
GithubGoldMiner commented Oct 27, 2017
Hi, I am not quite sure whether I have fully understand about your use case but could you try this: https://github.com/foreverjs/forever
ORESoftware commented Oct 27, 2017 •
Best thing to do is to launch a process which launches your app as a child process. The parent process can kill and restart the child process at will. I wrote a simple nodemon alternative, the source is here:
ronovar commented Oct 28, 2017
Thanks ORESoftware. but i have node application that check if node isMaster process and i need to restart master process not child process..because i do node process clustering and i im using node clustering to do heavy stuff there so master process is what i need to restart using console. i read that best aproach is using terminal command like above but not using child process and using spawn but i try few spawn commands but none works
gireeshpunathil commented Mar 26, 2018
@ronovar — is this still outstanding?
gireeshpunathil commented Mar 27, 2018
closing due to inactivity, please re-open if it is still outstanding.
rockyjvec commented Sep 24, 2018
I thought I’d share how I did this in hopes it might help someone else searching how to do the same thing. This issue was the first result on google when I was searching for how to do this.
I’m using rabbitmq to manage scalable puppeteer worker processes for PDF generation of HTML pages. I’m using a rabbitmq exchange to send messages to all the workers to restart or shutdown themselves. Here is the relevant code I am using to have the worker processes restart themselves:
Depending on how you originally start the process, you may need to change argv[1] and slice(2) to argv[0] and slice(1).
Hope that helps.
twome commented Mar 27, 2019 •
Single-statement version of @rockyjvec’s incredibly useful answer:
Источник
The NodeSource Blog
You have reached the beginning of time!
All Posts
How To
Running Your Node.js App With Systemd — Part 1
Chris Lea
in How To on Nov 01 2016
You’ve written the next great application, in Node, and you are ready to unleash it upon the world. Which means you can no longer run it on your laptop, you’re going to actually have to put it up on some server somewhere and connect it to the real Internet. Eek.
There are a lot of different ways to run an app in production. This post is going to cover the specific case of running something on a «standard» Linux server that uses systemd , which means that we are not going to be talking about using Docker, AWS Lambda, Heroku, or any other sort of managed environment. It’s just going to be you, your code, and terminal with a ssh session my friend.
Before we get started though, let’s talk for just a brief minute about what systemd actually is and why you should care.
What is systemd Anyway?
The full answer to this question is big, as in, «ginormous» sized big. So we’re not going to try and answer it fully since we want to get on the the part where we can launch our app. What you need to know is that systemd is a thing that runs on «new-ish» Linux servers that is responsible for starting / stopping / restarting programs for you. If you install mysql , for example, and whenever you reboot the server you find that mysql is already running for you, that happens because systemd knows to turn mysql on when the machine boots up.
This systemd machinery has replaced older systems such as init and upstart on «new-ish» Linux systems. There is a lot of arguably justified angst in the world about exactly how systemd works and how intrusive it is to your system. We’re not here to discuss that though. If your system is «new-ish», it’s using systemd , and that’s what we’re all going to be working with for the forseeable future.
What does «new-ish» mean specifically? If you are using any of the following, you are using systemd :
- CentOS 7 / RHEL 7
- Fedora 15 or newer
- Debian Jessie or newer
- Ubuntu Xenial or newer
Running our App Manually
I’m going to assume you have a fresh installation of Ubuntu Xenial to work with, and that you have set up a default user named ubuntu that has sudo privileges. This is what the default will be if you spin up a Xenial instance in Amazon EC2. I’m using Xenial because it is currently the newest LTS (Long Term Support) version available from Canonical. Ubuntu Yakkety is available now, and is even newer, but Xenial is quite up-to-date at the time of this writing and will be getting security updates for many years to come because of its LTS status.
Use ssh with the ubuntu user to get into your server, and let’s install Node.
Next let’s create an app and run it manually. Here’s a trivial app I’ve written that simply echoes out the user’s environment variables.
Using your text editor of choice (which should obviously be Emacs but I suppose it’s a free country if you want to use something inferior), create a file called hello_env.js in the user’s home directory /home/ubuntu with the contents above. Next run it with
You should be able to go to
in a web browser now, substituting 11.22.33.44 with whatever the actual IP address of your server is, and see a printout of the environment variables for the ubuntu user. If that is in fact what you see, great! We know the app runs, and we know the command needed to start it up. Go ahead and press Ctrl-c to close down the application. Now we’ll move on to the systemd parts.
Creating a systemd Service File
The «magic» that’s needed to make systemd start working for us is a text file called a service file. I say «magic» because for whatever reason, this seems to be the part that people block on when they are going through this process. Fortunately, it’s much less difficult and scary than you might think.
We will be creating a file in a «system area» where everything is owned by the root user, so we’ll be executing a bunch of commands using sudo . Again, don’t be nervous, it’s really very straightforward.
The service files for the things that systemd controls all live under the directory path
so we’ll create a new file there. If you’re using Nano as your editor, open up a new file there with:
and put the following contents in it:
Let’s go ahead and talk about what’s in that file. In the [Unit] section, the Description and Documentation variables are obvious. What’s less obvious is the part that says
That tells systemd that if it’s supposed to start our app when the machine boots up, it should wait until after the main networking functionality of the server is online to do so. This is what we want, since our app can’t bind to NODE_PORT until the network is up and running.
Moving on to the [Service] section we find the meat of today’s project. We can specify environment variables here, so I’ve gone ahead and put in:
so our app, when it starts, will be listening on port 3001. This is different than the default 3000 that we saw when we launched the app by hand. You can specify the Environment directive multiple times if you need multiple environment variables. Next is
which tells systemd how our app launches itself. Specifically, it lets systemd know that the app won’t try and fork itself to drop user privileges or anything like that. It’s just going to start up and run. After that we see
which tells systemd that our app should be run as the unprivileged ubuntu user. You definitely want to run your apps as unprivileged users to that attackers can’t aim at something running as the root user.
The last two parts here are maybe the most interesting to us
First, ExecStart tells systemd what command it should run to launch our app. Then, Restart tells systemd under what conditions it should restart the app if it sees that it has died. The on-failure value is likely what you will want. Using this, the app will NOT restart if it goes away «cleanly». Going away «cleanly» means that it either exits by itself with an exit value of 0 , or it gets killed with a «clean» signal, such as the default signal sent by the kill command. Basically, if our app goes away because we want it to, then systemd will leave it turned off. However, if it goes away for any other reason (an unhandled exception crashes the app, for example), then systemd will immediately restart it for us. If you want it to restart no matter what, change the value from on-failure to always .
Last is the [Install] stanza. We’re going to gloss over this part as it’s not very interesting. It tells systemd how to handle things if we want to start our app on boot, and you will probably want to use the values shown for most things until you are a more advanced systemd user.
Using systemctl To Control Our App
The hard part is done! We will now learn how to use the system provided tools to control our app. To being with, enter the command
You have to do this whenever any of the service files change at all so that systemd picks up the new info.
Next, let’s launch our app with
After you do this, you should be able to go to
in your web browser and see the output. If it’s there, congratulations, you’ve launched your app using systemd ! If the output looks very different than it did when you launched the app manually don’t worry, that’s normal. When systemd kicks off an application, it does so from a much more minimal environment than the one you have when you ssh into a machine. In particular, the $HOME environment variable may not be set by default, so be sure to pay attention to this if your app makes use of any environment variables. You may need to set them yourself when using systemd .
You may be interested in what state systemd thinks the app is in, and if so, you can find out with
Now, if you want to stop your app, the command is simply
and unsurprisingly, the following will restart things for us
If you want to make the application start up when the machine boots, you accomplish that by enabling it
and finally, if you previously enabled the app, but you change your mind and want to stop it from coming up when the machine starts, you correspondingly disable it
Wrapping Up
That concludes today’s exercise. There is much, much more to learn and know about systemd , but this should help get you started with some basics. In a follow up blog post, we will learn how to launch multiple instances of our app, and load balance those behind Nginx to illustrate a more production ready example.
Источник