温馨提示×

Node.js在CentOS上的网络配置如何设置

小樊
61
2025-09-02 03:02:01
栏目: 编程语言

一、系统网络配置

  1. 安装Node.js
    使用NodeSource仓库安装指定版本(如14.x):

    curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
    sudo yum install -y nodejs
    

    验证安装:node -vnpm -v

  2. 配置网络接口
    编辑网卡配置文件(如/etc/sysconfig/network-scripts/ifcfg-ens33):

    DEVICE=ens33
    BOOTPROTO=static  # 静态IP
    ONBOOT=yes
    IPADDR=192.168.1.100
    NETMASK=255.255.255.0
    GATEWAY=192.168.1.1
    DNS1=8.8.8.8
    

    重启网络:sudo systemctl restart network

  3. 防火墙设置
    开放Node.js所需端口(如80、443):

    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
    

    或针对特定端口:

    sudo firewall-cmd --permanent --add-port=3000/tcp
    sudo firewall-cmd --reload
    ```。  
    
    

二、Node.js应用网络配置

  1. 监听地址与端口
    在代码中指定监听IP和端口(如仅监听本地):

    const http = require('http');
    const server = http.createServer((req, res) => {
      res.end('Hello World\n');
    });
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
    });
    

    若需监听所有IP,将'127.0.0.1'改为'0.0.0.0'

  2. 使用环境变量
    通过环境变量动态配置端口和主机:

    const port = process.env.PORT || 3000;
    const host = process.env.HOST || '0.0.0.0';
    server.listen(port, host, () => {
      console.log(`Server running at http://${host}:${port}/`);
    });
    

    启动时指定:PORT=8080 HOST=0.0.0.0 node app.js

  3. 反向代理(可选)
    用Nginx代理Node.js应用,提升性能和安全性:

    • 安装Nginx:sudo yum install nginx
    • 配置代理(/etc/nginx/conf.d/nodejs.conf):
      server {
          listen 80;
          server_name example.com;
          location / {
              proxy_pass http://127.0.0.1:3000;
              proxy_set_header Host $host;
          }
      }
      
    • 重启Nginx:sudo systemctl restart nginx

三、验证与优化

  • 测试连通性ping example.comcurl http://localhost:3000
  • 监控工具:使用ssnetstat查看端口状态,top监控资源占用。
  • 安全优化:定期更新Node.js版本,限制IP访问(防火墙或应用层白名单)。

参考来源

0