how to set up an Express.js app on a live server, such as a VPS (Virtual Private Server) or a cloud service like DigitalOcean, AWS EC2, or Linode, and make it publicly accessible

Prerequisites
Before you start, ensure you have:
-
A VPS or cloud server (e.g., Ubuntu 20.04 or later)
-
Root or sudo access
-
A registered domain name (optional, but recommended)
-
Installed:
-
Node.js and npm
-
Git (optional, for deploying from GitHub)
-
Firewall configured (UFW or similar)
-
Step-by-Step: Setting Up Express.js on a Live Server
1. 🔌 Connect to Your Server
Use SSH to connect to your server:
ssh your-username@your-server-ip
2. Install Node.js and npm
On Ubuntu, install Node.js (use LTS version):
sudo apt update
sudo apt install nodejs npm -y
Check installation:
node -v
npm -v
3. Create Your Express App
Either clone from GitHub:
git clone https://github.com/yourusername/your-express-app.git
cd your-express-app
Or create a new app manually:
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
Create a file named server.js
:
// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello from Express on a live server!');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
4. Start the Express App
To run the server:
node server.js
Now visit:http://your-server-ip:3000
(Replace your-server-ip
with your actual IP)
5. Allow Traffic Through Firewall
If you're using UFW:
sudo ufw allow 3000
To allow HTTP (port 80):
sudo ufw allow 80
6. Run the App in Background (Forever)
Install PM2, a process manager for Node.js:
sudo npm install -g pm2
Start your app with PM2:
pm2 start server.js
Enable startup script (auto-run after reboot):
pm2 startup
pm2 save
7. Set Up Domain Name (Optional but Recommended)
If you have a domain name:
-
Point the domain’s A record to your server IP.
-
Install Nginx as a reverse proxy:
sudo apt install nginx
Edit Nginx config:
sudo nano /etc/nginx/sites-available/default
Replace contents with:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
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;
}
}
Restart Nginx:
sudo systemctl restart nginx
Now visit:http://yourdomain.com
8. (Optional) Secure with HTTPS using Let's Encrypt
Install Certbot:
sudo apt install certbot python3-certbot-nginx
Run Certbot:
sudo certbot --nginx -d yourdomain.com
This will configure HTTPS automatically.
Summary
Step | Task |
---|---|
1️⃣ | SSH into server |
2️⃣ | Install Node.js & npm |
3️⃣ | Create Express app |
4️⃣ | Run app (node or pm2 ) |
5️⃣ | Open firewall port |
6️⃣ | (Optional) Reverse proxy with Nginx |
7️⃣ | (Optional) Link domain and use HTTPS |