Xây Dựng và Triển Khai Máy Chủ Node.js Trên Ubuntu

Tạo Máy Chủ Node.js Cơ Bản

Sử dụng Express để khởi tạo dịch vụ web:

const server = require('express')();
const http = require('http');
const fs = require('fs');
const path = require('path');

server.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Content-Type', 'text/html');
  next();
});

server.use('/assets', express.static(path.join(__dirname, 'public')));
server.get('/', (req, res) => {
  fs.readFile(path.join(__dirname, 'public', 'index.html'), 'utf8', (err, content) => {
    if (err) return res.status(500).send('Lỗi hệ thống');
    res.send(content);
  });
});

const PORT = 8080;
http.createServer(server).listen(PORT, () => {
  console.log(`Dịch vụ đang chạy tại http://localhost:${PORT}`);
});

Tạo file public/index.html với nội dung đơn giản:

<!DOCTYPE html>
<html>
<body>
  <h1>Hệ thống đã sẵn sàng</h1>
</body>
</html>

Chạy lệnh node app.js để khởi động dịch vụ.

Cấu Hình Máy Chủ Ubuntu

Cài đặt công cụ cần thiết:

sudo apt update
sudo apt install -y git curl net-tools

Thiết lập SSH để truy cập từ xa:

sudo apt install -y openssh-server
sudo ufw allow 22
sudo systemctl restart ssh

Kiểm tra kết nối bằng lệnh ssh username@your_server_ip.

Quản Lý Phiên Bản Node.js

Sử dụng NVM để cài đặt Node.js:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18.18.0
nvm alias default 18.18.0

Kiểm tra phiên bản: node -v.

Triển Khai Dịch Vụ Với PM2

Cài đặt PM2 và khởi động ứng dụng:

npm install pm2 -g
pm2 start app.js --name "web-service" --watch
pm2 save
pm2 startup

Kiểm tra trạng thái dịch vụ:

pm2 status
curl http://localhost:8080

Cấu Hình Nginx Làm Proxy Ngược

Tạo file cấu hình tại /etc/nginx/sites-available/web-app:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /static/ {
        root /var/www/app/public;
        expires 30d;
    }
}

Kích hoạt cấu hình:

sudo ln -s /etc/nginx/sites-available/web-app /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Mở cổng 80 nếu sử dụng tường lửa:

sudo ufw allow 80

Truy cập địa chỉ máy chủ qua trình duyệt để kiểm tra hoạt động.

Thẻ: Express Koa PM2 nginx Ubuntu

Đăng vào ngày 18 tháng 5 lúc 23:35