The script creates a nodejs user, installs Node Version Manager (NVM), Node.js (version 22), PM2 (a process manager), and Nginx as a reverse proxy, and configures them for deploying Node.js applications.
- Creates a nodejs user with a home directory (/home/nodejs) and Bash shell.
- Adds nodejs to the sudo group.
- Sets the user password to password.
- Runs as nodejs user via sudo -H -u nodejs to ensure correct home directory (/home/nodejs).
- Downloads and installs NVM (v0.40.3) from https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh.
- Configures .bashrc to source NVM automatically:
- Adds export NVM_DIR=”$HOME/.nvm”.
- Adds NVM script and bash completion.
- Sources .bashrc to make NVM available in the script.
- Installs Node.js 22 via NVM as nodejs user.
- Sets it as the default version: nvm alias default 22.
- Updates npm globally: npm install -g npm.
- Installs PM2 globally as nodejs user: npm install -g pm2.
- Configures PM2 to start on boot by generating and executing a systemd startup command.
- Installs Nginx: apt install -y nginx.
- Configures a default Nginx site in /etc/nginx/sites-available/default:
- Listens on port 80.
- Proxies requests to http://localhost:3000 (assumed Node.js app port).
- Includes headers for WebSocket support and client IP forwarding.
- Restarts and enables Nginx: systemctl restart nginx, systemctl enable nginx.
NodeJS app setup:
- Login via ssh to your server.
- Use the following commands in order:
- su – nodejs
- mkdir /home/nodejs/your-app
- git clone your_repo.git /home/nodejs/your-app
- cd /home/nodejs/your-app
- npm install –omit=dev
- pm2 start app.js –name your-app-name
- pm2 save
- Adjust your app’s port to 3000 or update the NGINX config accordingly (edit /etc/nginx/sites-available/default, test with nginx -t, and restart systemctl restart nginx).
- Your app is accessible at http://<server-ip>
- Notes:
- The nodejs user has sudo access.
- Change nodejs user password: passwd nodejs.
- Enable HTTPS with Certbot: apt install certbot python3-certbot-nginx, then certbot –nginx.
OS: Ubuntu 24.04
Variables:
- NVM_VERSION: Node.js version (default: 22).
- NODEJS_USER_PASSWORD: Password for nodejs user.
Important Files and Directories:
- /home/nodejs/.nvm/: NVM and Node.js installations.
- /home/nodejs/.bashrc: Configures NVM sourcing.
- /etc/nginx/sites-available/default: Nginx configuration for proxying to Node.js.
- /usr/lib/node_modules/pm2/: PM2 installation.
- /var/www/html: Default web root.
- Logs:
- Nginx: /var/log/nginx/{access.log,error.log}.
- PM2: pm2 logs or ~/.pm2/logs/ (as nodejs user).
- Node.js app: Managed by PM2 or app-specific logs.
Future Enhancements:
- Add HTTPS setup with Certbot.
- Include app deployment example in the script.
- MongoDB integration.