How to automatically start a NodeJs Express server when EC2 starts

33 Views Asked by At

I have an EC2 instance Linux/UNIX, t2.micro. Al there is in there is a NodeJs Express server. If I cd ./project-folder-name and then run "npm run server" it starts a server which can accept API requests. I use this server only 15 minutes a day so I am thinking to have it in a schedule to stop/start only for 1 hour. I got the code that starts and stops it but I don't know how to make the EC2 to start the Express server (go to the path and run "npm run server") after the EC2 is restarted. Note: No need to worry about pulling the project from gitlab or updating dependencies (npm install or any other command). Literally, all I want it is to get to the folder and run "npm run server", which is a script on my package.json file

I appreciate if someone can give me some instructions on how to do that.

1

There are 1 best solutions below

0
Athavan T On

You can make use of custom systemd service. Creating a custom systemd service in Ubuntu enables users to start, stop, and manage custom background processes effectively.

create a bash script file with the required commands to run your node application.

in my_node_app.sh

#!/bin/bash
# Custom script to node application
cd /path/to/node/app/folder
npm install
npm run server

make the script executable chmod +x /path/to/script/my_node_app.sh

Create a new unit file at /etc/systemd/system/my_node_app.service

[Unit]
Description=My Custom Service

[Service]
Type=simple
ExecStart=/path/to/script/my_node_app.sh

[Install]
WantedBy=multi-user.target

Execute the following commands to reload, enable and start the service

systemctl daemon-reload
systemctl enable my_node_app.service
systemctl start my_node_app.service

After starting the services every time instance reboot this service will run the script.