What is the best way to initiate a node.js application automatically on an Amazon Linux AMI instance in AWS?

Could someone provide a simple guide on how to start an application when the instance starts up and is running? If the service was installed using yum, can I use /sbin/chkconfig to add it as a service?

But what if I want to run a program that wasn't installed through yum? For example, to run a node.js program, I currently have to execute the script sudo node app.js in my home directory every time the system boots up.

Being unfamiliar with Amazon Linux AMI, I'm having difficulty finding the proper way to automatically run a script on each boot. Is there a more elegant solution for accomplishing this task?

Answer №1

If you want your app to automatically start when Linux loads and restart if it crashes, creating an upstart job is the way to go. You can easily manage your app by using commands like sudo start yourapp, sudo stop yourapp, and sudo restart yourapp.

Follow these steps to set up an upstart job:

1) Install the upstart utility. It may already be installed on a standard Amazon Linux AMI:

sudo yum install upstart

For Ubuntu:

sudo apt-get install upstart

2) Create an upstart script for your node application:

In the /etc/init directory, create a file named yourappname.conf with the following code:

#!upstart
description "Your App Name"

start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

env NODE_ENV=development

# Warning: running node as root user can pose security risks
exec node /path_to_your_app/app.js >> /var/log/yourappname.log 2>&1

3) Start your app using the command sudo start yourappname

Answer №2

If you need to run a Node.js script as a service and have it automatically start during system boots, then forever-service is the way to go. Just execute the following commands:

npm install -g forever-service
forever-service install test

By running these commands, you will set up app.js in the current directory as a service using forever. This service will restart itself every time the system reboots. Additionally, it attempts a graceful stop when manually stopped. The script also includes provisions for logrotate.

You can find the Github repository at: https://github.com/zapty/forever-service

Currently, forever-service supports Amazon Linux, CentOS, and Redhat. Support for other Linux distributions, Mac, and Windows is currently in progress.

Please note that I am the developer of forever-service.

Answer №3

I chose to run my Amazon Linux instance on Ubuntu and utilized systemd for setup.

The first step is creating a <servicename>.service file, in my case it was cloudyleela.service.

sudo nano /lib/systemd/system/cloudyleela.service

Within this file, input the following:

[Unit]
Description=cloudy leela
Documentation=http://documentation.domain.com
After=network.target

[Service]
Type=simple
TimeoutSec=0
User=ubuntu
ExecStart=/usr/bin/node /home/ubuntu/server.js
Restart=on-failure

[Install]
WantedBy=multi-user.target

This configuration launches the node application with a set restart policy in case of failure. Amazon instances come without default user passwords.

Once you reload the file from disk, you can start your service. Enabling it will activate the service, automatically starting it during boot-up.

ubuntu@ip-172-31-21-195:~$ sudo systemctl daemon-reload
ubuntu@ip-172-31-21-195:~$ sudo systemctl start cloudyleela
ubuntu@ip-172-31-21-195:~$ sudo systemctl enable cloudyleela
Created symlink /etc/systemd/system/multi-user.target.wants/cloudyleela.service → /lib/systemd/system/cloudyleela.service.
ubuntu@ip-172-31-21-195:~$

Find an excellent systemd tutorial for node.js here.

If running a webserver:

You might encounter issues running the webserver on port 80. An easy workaround is running it on a different port (e.g. 4200) and redirecting traffic from that port to port 80 using this command:

sudo iptables -t nat -A PREROUTING -i -p tcp --dport 80 -j REDIRECT --to-port 4200

Unfortunately, this method is not persistent and needs to be repeated after server restart. A better practice is incorporating this command into the service script:

  1. ExecStartPre for adding port forwarding
  2. ExecStopPost for removing port forwarding
  3. PermissionStartOnly for executing with sudo permissions

Example:

[Service]
...
PermissionsStartOnly=true
ExecStartPre=/sbin/iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 4200
ExecStopPost=/sbin/iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 4200

Don't forget to reload and restart your service:

[ec2-user@ip-172-31-39-212 system]$ sudo systemctl daemon-reload
[ec2-user@ip-172-31-39-212 system]$ sudo systemctl stop cloudyleela
[ec2-user@ip-172-31-39-212 system]$ sudo systemctl start cloudyleela
[ec2-user@ip-172-31-39-212 system]$

For microservices (update on Dec 2020)

While the previous solution offers flexibility, setting it up takes time. With multiple applications, this process becomes cumbersome. PM2 simplifies this by managing all applications under one service.

PM2 can also install its own service during initial setup.

npm install pm2 -g

Adding new services is straightforward:

pm2 start index.js --name "foo"` 

To ensure automatic startup on reboot, save the setup with:

pm2 save

Use pm2 list to view all running node applications.

Additionally, PM2 provides an online dashboard for remote monitoring but some features may require licensing.

Answer №4

If you're looking for a quick fix, you can simply start your app from /etc/rc.local by adding your command there.

For a more elegant solution, consider packaging your application into an rpm file, creating a startup script to place in /etc/rc.d so that you can use chkconfig on your app, and then installing the rpm on your instance.

You may find this or this helpful (or simply search 'creating rpm packages' on Google).

Answer №5

If you need to automate the start and stop of your application, consider creating a script that follows chkconfig's conventions and placing it in /etc/init.d. This will allow you to set your script to start when other services are started.

You can refer to an existing script in /etc/init.d as a template. This article outlines the requirements including:

  • An executable script with the necessary shell identifier (e.g., #!/bin/bash)
  • A comment in the format # chkconfig: where levels 345 indicate startup priorities, and startprio and stopprio define the order for starting and stopping services respectively. You can use an existing service as a reference for these values.

Once your script is prepared, you can run the following commands:

chkconfig --add yourscript 
chkconfig yourscript on 

This should configure your script correctly. In some distributions, you may need to manually create a symbolic link to /etc/init.d/rc.d, although AWS distros often handle this step automatically when enabling the script.

Answer №6

Consider utilizing Elastic Beanstalk for easy deployment and support with features like auto-scaling, SSL termination, and blue/green deployments.

If you prefer a more hands-on approach using a RedHat based linux distro (such as Amazon Linux), familiarize yourself with systemd, as suggested by @bvdb in the previous answer:

https://en.wikipedia.org/wiki/Systemd

Create a custom AMI on an EC2 instance after setting everything up to avoid repetitive setup processes. Utilize load balancers for better uptime in production environments. You may also want to explore using pm2 along with systemd, as advised by @bvdb.

The learning curve for all this can be steep, especially for newcomers. Consider platforms like Elastic Beanstalk or Google App Engine for simpler cloud deployment without the complexity.

In my current development workflow, I use TypeScript deployed to serverless functions in the cloud, eliminating the need to worry about package installations or app startup.

Answer №7

To initiate your application on startup, utilize the screen command. Open your crontab file by running crontab -e and insert the following line:

@reboot  screen -d -m bash -c "cd /home/user/yourapp/; node app"

Answer №8

Been utilizing forever on my AWS server with great success. Simply install it using

 [sudo] npm install forever -g

To add a new application, use

 forever start path_to_application

When you need to stop the application, use

 forever stop path_to_application

I found this article particularly helpful when setting everything up.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up webRTC and Express.js to function within the same domain requires proper configuration

Currently, I am in the process of creating a video conferencing website using node.js and express.js rather than apache. However, I am faced with some challenges when deciding on the best approach. The main goal is to have the server deliver the website t ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

Node.js Error: expressJWT is not recognized as a valid function

Hey there, I'm fairly new to working with nodeJs. Currently facing an error that's quite puzzling for me. Here is a snippet from my package.json : { "name": "pangolinapp", "version": "1.0.0", " ...

Troubleshooting the Angular Fullstack + CORS issue: "XMLHttpRequest cannot load

I've been wracking my brain trying to figure this out. Utilizing the yeoman generator angular-fullstack, I created a simple Angular app on a NodeJS server with Express. The app makes remote service calls, so there are no API server side calls within ...

Issues with connecting to Socket.IO in Cordova app

I'm having troubles setting up my Cordova app to establish a socket.io websocket connection. Despite following the instructions I found, it doesn't seem to connect when running in debug mode. Can anyone help me troubleshoot this issue? Server Si ...

Jade Parser issue: "Anonymous blocks must be part of a mixin to be allowed" error

Encountering this error: "Anonymous blocks are not permitted unless they belong to a mixin" while working with this Jade file: html body style(type='text/css', media='screen') div#div_name display: b ...

Error: CORS issue with Axios request on Node backend and Vue frontend with Vite

This particular issue has been the subject of numerous discussions on various platforms, including Stackoverflow. Despite my best efforts, I have not been able to find a solution that works for me. In essence, I am currently developing an API using Node JS ...

Start numerous nodejs servers with just a single command

I currently have multiple Nodejs servers, each stored in its own separate folder within a root directory. Whenever I need to run these servers, I find it cumbersome to navigate through each folder and manually type nodemon *name*. The number of servers i ...

Timeout occurs in method calls when using socket.io and socket.io-redis adapter together

After recently transitioning from Socket.io 2.x to 3.0.3 and integrating it with [email protected], I encountered an issue. Following the instructions provided in the original migration documentation, I attempted to retrieve a list of all open socket ...

Create a variety of web pages with the powerful Quasar framework

Currently, I am facing a challenge in creating a multi-page website with Quasar to be deployed on Netlify. It seems that Quasar is only generating the index.html file. I have attempted to use both Quasar build and Quasar build --mode ssr, but unfortunatel ...

Using the AND operator in MySQL with the Express framework: a comprehensive guide

I'm looking to create a query using the AND operator in the Express framework with MySQL. MySQL Query: select * from questions where question_id=1 AND answer="apple" AND appkey="1122"; I want to implement the above query in Express.js with MySQL. He ...

NextJS will redirect the user back to the previous router they came from following authentication

Hello! I am currently facing a challenge in redirecting a user back to the initial page they clicked on after being authenticated. The issue lies in server-side rendering (SSR) and the lack of access to the window.history object in getServerSideProps. The ...

Angular in production - ways to identify the packages being utilized (without utilizing npm)

I am facing a challenge with my production Linux environment, as I do not want to install npm or nodejs. The system currently hosts an asp.net core application and I need to verify if a specific package, postcss, is being used. During development, I notic ...

Why is jQuery ajax not functioning in the view file in a node.js environment?

I have recently started working with Express Node.js and I am facing an issue with making an AJAX call or using jQuery from the HBS view. Below are my controller methods: router.get('/', function(req, res) { console.log("home get request"); ...

Tips on retrieving a single matching record in a many-to-many relationship using Postgres

In an effort to retrieve a user's pet based on the user's id and the pet's id. Description of my tables: CREATE TABLE pet_owner ( id serial PRIMARY KEY, first_name varchar(100) NOT NULL, last_name varchar(100) NOT NULL, phone_number ...

Troubleshooting ng-view with partials in AngularJS/Express: What to do when it

Everything was working fine until I attempted to display a partial file in ng-view. /public/app/app.js angular.module('app', ['ngResource', 'ngRoute']); angular.module('app').config(function($routeProvider,$locati ...

The website at localhost with port number 3003 encountered an error with the socket.io connection, specifically in the polling transport mechanism with a reference code of OZxtDFc

Seeking assistance with socket.io chat implementation. I have different routes for various URLs, but encountering transport polling errors after the server initially works. Despite making several changes to ensure that socket uses session middleware func ...

Uploading a Node.js package to npm using Windows Subsystem for Linux: the secrets to successful authentication

While working on a Node.js module in WSL (Ubuntu on Windows), I encountered an issue when attempting to publish it using npm adduser. The command provided the following output: username@my-pc:/mnt/c/Users/username/workspace/demo-node$ npm adduser npm notic ...

Adding a prefix to the imported CSS file

My React app, created with create-react-app, is designed to be integrated as a "widget" within other websites rather than functioning as a standalone application. To achieve this, I provide website owners with minified JS and CSS files that they can inser ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...