Как использовать Forever With Express для поддержания работы сервера NodeJS?

У меня есть сервер Express NodeJS, который я вручную запускаю через терминал с npm start в корневой папке моего проекта. Я скачал и установил пакет Forever глобально. Когда я запускаю Forever против моего файла app.js, используя:

forever start app.js

мой сервер не запускается. Я предполагаю, что это связано с тем, что в файле app.js нет явной команды createServer. Какой файл я должен запустить против команды forever start, чтобы запустить мой сервер?


person Lloyd Banks    schedule 01.08.2014    source источник


Ответы (4)


На моем сервере узлов я использую npm forever:

sudo forever start app.js

Обратите внимание, что вам нужно sudo это

person Sterling Archer    schedule 01.08.2014
comment
Я пробовал это с sudo, но сервер все еще не работает. Я не получаю сообщение об ошибке терминала, поэтому кажется, что команда прошла, но не в правильном файле. Если я начну с npm start, я смогу попасть в конечную точку, которую настроил, но с forever start конечная точка не работает - person Lloyd Banks; 01.08.2014
comment
ваше приложение слушает? - person Sterling Archer; 01.08.2014

Все, что вам нужно сделать, это запустить в папке вашего проекта команду forever start ./bin/www, и все будет хорошо :)

person Danilo    schedule 15.12.2015

Сначала я создаю сценарий Upstart. Я использую Amazon EC2 AMI, но есть и другие подобные инструменты для других ОС.

# This is an upstart (http://upstart.ubuntu.com/) script
# to run the node.js server on system boot and make it
# manageable with commands such as
# 'start app' and 'stop app'
#
# This script is to be placed in /etc/init to work with upstart.
#
# Internally the 'initctl' command is used to manage:
# initctl help
# initctl status node-app
# initctl reload node-app
# initctl start node-app

description "node.js forever server for app"

#node child process might not really fork, so don't except it
#expect fork

# used to be: start on startup
# until we found some mounts weren't ready yet while booting:

start on runlevel [2345]
stop on runlevel [016]

# Automatically Respawn:
respawn
respawn limit 99 5

chdir /path/to/directory/node-app

exec node start.js

#post-start script
#   # Optionally put a script here that will notifiy you node has (re)started
#   # /root/bin/hoptoad.sh "node.js has started!"
#end script

Затем я использовал файл start.js, в котором «размещено» мое приложение. Мое настоящее приложение находится в index.js. Вы можете пропустить материал process.on внизу, но мне он там нравится.

/*jslint node: true */
"use strict";

/**
 * File to start using forever, logs crashes, restarts on file changes, etc.
 */

var cmd = ( process.env.DBG ? "node --debug" : "node" );

var forever = require( 'forever' ),
  //exec = require('child_process').exec,
  child = new( forever.Monitor )( 'index.js', {
    'silent': false,
    'pidFile': 'pids/node-app.pid',
    'watch': true,
    'command': cmd,
    //"max" : 10,
    'watchDirectory': './lib', // Top-level directory to watch from.
    'watchIgnoreDotFiles': true, // whether to ignore dot files
    'watchIgnorePatterns': [], // array of glob patterns to ignore, merged with contents of watchDirectory + '/.foreverignore' file
    'logFile': 'logs/forever.log', // Path to log output from forever process (when daemonized)
    //'outFile': 'logs/forever.out', // Path to log output from child stdout
    'errFile': 'logs/forever.err'
  } );

child.on( "exit", function() {
  console.log( 'node-app has exited!' );
} );
child.on( "restart", function() {
  console.log( 'node-app has restarted.' );
} );


child.start();
forever.startServer( child );

process.on( 'SIGINT', function() {
  console.log( "\nGracefully shutting down \'node forever\' from SIGINT (Ctrl-C)" );
  // some other closing procedures go here
  process.exit();
} );

process.on( 'exit', function() {
  console.log( 'About to exit \'node forever\' process.' );
} );

process.on( 'uncaughtException', function( err ) {
  console.log( 'Caught exception in \'node forever\': ' + err );
} );

Работает на меня! Вы можете пропустить выскочку, если просто хотите, чтобы ваше приложение продолжало работать — это мое производственное решение.

person clay    schedule 04.08.2014

forever -w ./bin/www 

В папке вашего проекта запустите команду forever -w ./bin/www. Это сработало для меня. Я уверен, что это сработает для вас.

person Gourab Sarkar    schedule 04.04.2016