This used as a user data script for Amazon Linux 2 Ec2 Instances will do the following
Install Git
Install Nginx
Setup Nginx as a Reverse Proxy for your Node.js Application
Install Node using NVM
Install PM2
Run a Dummy API Server Using express
Start the Server using PM2
#! /bin/bash
cd /home/ec2-user/
sudo yum update -y
sudo yum install git -y
# # when installing on Amazon Linux AMI, use:
# # sudo yum install nginx -y
# # when installing on Amazon Linux 2 AMI, use
sudo amazon-linux-extras install nginx1.12 -y
sudo cat > /etc/nginx/nginx.conf << EOL
user nginx;
worker_processes auto;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
error_log /dev/null;
access_log /dev/null;
include /etc/nginx/mime.types;
default_type application/octet-stream;
upstream express_server {
server 127.0.0.1:3001;
keepalive 64;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_set_header X-Forwarded-For \$ proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP \$ remote_addr;
proxy_set_header Host \$ http_host;
proxy_set_header Upgrade \$ http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_pass http://express_server/;
proxy_redirect off;
proxy_read_timeout 240s;
}
}
}
EOL
sudo chkconfig nginx on
sudo service nginx start
sudo service nginx restart
cat > /tmp/subscript.sh << EOF
# START
echo "Setting up NodeJS Environment"
curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
echo 'export NVM_DIR="/home/ec2-user/.nvm"' >> /home/ec2-usr/.bashrc
echo '[ -s "\$ NVM_DIR/nvm.sh" ] && . "\$ NVM_DIR/nvm.sh" # This loads nvm' >> /home/ec2-user/.bashrc
# Dot source the files to ensure that variables are available within the current shell
. /home/ec2-user/.nvm/nvm.sh
. /home/ec2-user/.bashrc
# Install NVM, NPM, Node.JS & Grunt
nvm install v10.16.3
nvm use v10.16.3
nvm alias default v10.16.3
npm install -g pm2
curl -o- -L https://yarnpkg.com/install.sh | bash
export PATH="\$ HOME/.yarn/bin:\$ HOME/.config/yarn/global/node_modules/.bin:\$ PATH"
mkdir api
cd api
yarn init -y
yarn add express
cat > ./app.js <<EOL
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello World!");
});
app.listen(3001);
EOL
pm2 start app.js
EOF
chown ec2-user:ec2-user /tmp/subscript.sh && chmod a+x /tmp/subscript.sh
sleep 1; su - ec2-user -c " /tmp/subscript.sh"
I had to add backslash
\
to all the$
s used in the script as shell attempts to read it as a variable.Also, I need to test if the setup works after a reboot.Working now. Make sure topm2 save
every time you deploy a new version.