Running a Node.js Server on Ubuntu: A Step-by-Step Guide
In this guide, we will cover the following:
-
Installation
Set up your server environment by installing the necessary software. -
Setup
Configure your server to run your Node.js application.
We will install and configure the following:
-
Nginx
A high-performance web server that can also act as a reverse proxy for your Node.js application. -
Node.js
A JavaScript runtime built on Chrome’s V8 JavaScript engine, designed to build scalable network applications. -
Yarn
A fast, reliable, and secure dependency management tool for JavaScript. -
PM2
An advanced process manager for Node.js applications, designed to keep your app running smoothly. -
MongoDB
A NoSQL database that provides high performance, high availability, and easy scalability. -
Git
A version control system to manage your codebase effectively.
INSTALLATION PART for Linux (Ubuntu System)
-
Install Nginx
sudo apt-get update sudo apt-get install nginx
-
Install Node.js
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - sudo apt-get install -y nodejs
-
Install Yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list sudo apt-get update sudo apt-get install yarn
-
Install PM2
sudo npm install -g pm2
-
Install MongoDB
sudo apt-get install -y mongodb sudo systemctl start mongodb sudo systemctl enable mongodb
Adding an Administrative User:
mongo use admin db.createUser({user: "admin", pwd: "password", roles:[{role:"userAdminAnyDatabase", db: "admin"}]}) exit
SETUP PART
Node.js Server
-
Run the Server Using PM2
Navigate to your project directory and start the server:
pm2 start app.js --name my-node-app
Note: Ensure app.js is the entry point of your application.
Your Node.js application will now be accessible at:
http://<SERVER_ADDRESS>:<PORT>
- SERVER_ADDRESS: The IP address or domain name of your server.
- PORT: The port on which your Node.js server is running.
-
Configure Nginx as a Reverse Proxy
- Create a new Nginx configuration file in
/etc/nginx/sites-available/
:
sudo nano /etc/nginx/sites-available/my-node-app
- Add the following configuration:
server { listen 80; server_name <SERVER_ADDRESS>; location / { proxy_pass http://localhost:<PORT>; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
- Enable the configuration by creating a symbolic link:
sudo ln -s /etc/nginx/sites-available/my-node-app /etc/nginx/sites-enabled/
- Reload and restart Nginx to apply changes:
sudo systemctl reload nginx sudo systemctl restart nginx
- Create a new Nginx configuration file in
What did I miss? Let me know in the comments and I’ll add it in!