انتقل إلى المحتوى

الدروس الخوادم متوسط1 دقائق قراءة

How to Deploy a Node.js App on a VPS with PM2 and Nginx

Run a Node.js application in production: install Node.js, keep it running with PM2, start it on boot, and serve it through Nginx with HTTPS.

بواسطة فريق تحرير ZSOLNET آخر تحديث

هذه الصفحة غير متاحة بالعربية بعد، لذا تُعرض بالإنجليزية.

أهم النقاط

  • PM2 restarts your app if it crashes and when the server reboots.
  • Put Nginx in front as a reverse proxy for HTTPS and static files.
  • Bind the app to localhost so it's only reachable through Nginx.

1. Install Node.js LTS

Using the NodeSource repository (replace 22 with the current LTS major version):

curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install nodejs
node -v

2. Get your app onto the server

git clone https://github.com/you/app.git ~/app
cd ~/app && npm ci --omit=dev

Make the app listen on 127.0.0.1 and a port such as 3000.

3. Run it with PM2

sudo npm install -g pm2
pm2 start npm --name app -- start
pm2 save
pm2 startup systemd   # run the command it prints

4. Put Nginx in front

server {
    server_name example.com www.example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Enable the site, run sudo nginx -t && sudo systemctl reload nginx, then add HTTPS with Certbot.

Deploy updates

cd ~/app && git pull && npm ci --omit=dev && pm2 reload app

الأسئلة الشائعة

Which Node.js version should I use?

The current LTS (long-term support) release, unless your app requires a specific version.

How do I see my app's logs?

Run pm2 logs app-name, or pm2 monit for a live dashboard.

شارك X LinkedIn Facebook

الدخول إلى حسابك

أدِر نطاقاتك واستضافتك وفواتيرك من مكان واحد.

اتصال آمن مباشرة مع منطقة العملاء في ZSOLNET.

افتح لوحة تحكم ZSOLNET

ليس لديك حساب؟