Last active
February 26, 2019 13:43
-
-
Save khaledosman/3b4afad35c82eb4fce3de8a365c8fce7 to your computer and use it in GitHub Desktop.
Graceful start & Shutdown of NodeJS application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Graceful start & Graceful shutdown of application to prevent errors with ongoing requests on restarting https://pm2.io/doc/en/runtime/best-practices/graceful-shutdown/?utm_source=pm2&utm_medium=website&utm_campaign=rebranding | |
| const server = http.createServer(app) | |
| mongoose.connect(process.env.MONGO_URL) | |
| .then(db => { | |
| console.log('connected to mongo successfully') | |
| server.listen(port, err => { | |
| if (err) { | |
| console.log('something bad happened', err) | |
| } else { | |
| process.send = process.send || function () { } | |
| process.send('ready') | |
| console.log(`server is listening on ${port}`) | |
| } | |
| }) | |
| }) | |
| .catch(err => console.log('Mongo connection error', err)) | |
| // If the Node process ends, close the Mongoose connection | |
| const sigs = ['SIGINT', 'SIGTERM', 'SIGQUIT'] | |
| sigs.forEach(sig => { | |
| process.on(sig, () => { | |
| // Stops the server from accepting new connections and finishes existing connections. | |
| server.close(function (err) { | |
| if (err) { | |
| console.error(err) | |
| process.exit(1) | |
| } | |
| // close your database connection and exit with success (0 code) | |
| // for example with mongoose | |
| mongoose.connection.close(function () { | |
| console.log('Mongoose connection disconnected') | |
| process.exit(0) | |
| }) | |
| }) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment