linux

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

小樊
44
2025-07-01 11:37:46
栏目: 云计算

在Linux服务器上配置Node.js通常涉及以下几个步骤:

安装Node.js

  1. 使用包管理器
  1. 使用NodeSource二进制分发库
  1. 使用nvm(Node Version Manager)

配置环境变量

  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
看了该问题的人还看了