溫馨提示×

Linux服務器上Node.js如何配置

小樊
42
2025-07-01 11:37:46
欄目: 云計算

在Linux服務器上配置Node.js通常涉及以下幾個步驟:

安裝Node.js

  1. 使用包管理器
  • 對于基于Debian的系統(如Ubuntu),可以使用以下命令:

    sudo apt update
    sudo apt install nodejs npm
    
  • 對于基于Red Hat的系統(如CentOS或Fedora),可以使用以下命令:

    sudo yum install nodejs npm
    

    或者對于較新的版本,使用 dnf

    sudo dnf install nodejs npm
    
  1. 使用NodeSource二進制分發庫
  • 如果你需要特定版本的Node.js,可以使用NodeSource的二進制分發庫。例如,安裝Node.js 16.x版本:

    curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  1. 使用nvm(Node Version Manager)
  • 安裝nvm:

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    
  • 加載nvm到當前shell會話:

    source ~/.bashrc
    
  • 使用nvm安裝Node.js:

    nvm install node
    

    或者安裝特定版本:

    nvm install 16.14.0
    

配置環境變量

  1. 編輯用戶的shell配置文件(例如 ~/.bashrc~/.zshrc),將Node.js和npm的路徑添加到環境變量中:

    export PATH=$PATH:/usr/local/bin
    
  2. 使環境變量生效:

    source ~/.bashrc
    

驗證安裝

在終端里分別嘗試以下命令查看對應版本號:

node -v
npm -v

如果有返回具體的數值說明一切正常。

配置Node.js應用

  1. 創建一個簡單的Node.js應用(例如 index.js):

    const http = require('http');
    const hostname = '127.0.0.1';
    const port = 3000;
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello World
    

'); }); server.listen(port, hostname, () => { console.log(Server running at http://${hostname}:${port}/); });


2. 運行應用:

```bash
node index.js

在本地瀏覽器中訪問 http://127.0.0.1:3000/,查看項目是否正常運行。

安全性配置(可選)

  1. 使用HTTPS協議:

    const https = require('https');
    const fs = require('fs');
    const privateKey = fs.readFileSync('path/to/private-key.pem', 'utf8');
    const certificate = fs.readFileSync('path/to/certificate.pem', 'utf8');
    const ca = fs.readFileSync('path/to/ca.pem', 'utf8');
    const credentials = { key: privateKey, cert: certificate, ca: ca };
    const app = express();
    app.get('/', (req, res) => { res.send('Hello World!
    

'); }); const httpsServer = https.createServer(credentials, app); httpsServer.listen(443, () => { console.log(‘HTTPS server listening on port 443’); });


2. 限制訪問IP地址:

```javascript
const allowedIps = ['192.168.1.100', '192.168.1.101'];
app.use((req, res, next) => {
  const clientIp = req.connection.remoteAddress;
  if (allowedIps.includes(clientIp)) {
    next();
  } else {
    res.status(403).send('Access denied
');
  }
});

以上步驟涵蓋了在Linux系統上安裝、配置Node.js服務器的整個過程,并包括了一些基本的安全性配置建議。根據您的具體需求,您可能還需要進行其他配置,例如設置防火墻規則、配置日志記錄等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女