Node.js在Debian上的网络配置分为系统网络配置和Node.js应用网络配置两部分,具体步骤如下:
使用文本编辑器(如nano)修改/etc/network/interfaces,配置静态IP或DHCP:
sudo nano /etc/network/interfaces  
# 添加以下内容(根据实际网络修改)  
auto eth0  
iface eth0 inet static  
address 192.168.1.100  
netmask 255.255.255.0  
gateway 192.168.1.1  
dns-nameservers 8.8.8.8 8.8.4.4  
auto eth0  
iface eth0 inet dhcp  
sudo systemctl restart networking  
ping www.google.com  
若能ping通,说明网络配置成功。
在Node.js代码中,通过listen()方法指定IP和端口:
const http = require('http');  
const hostname = '127.0.0.1'; // 绑定本地IP(或改为服务器实际IP)  
const port = 3000;  
const server = http.createServer((req, res) => {  
  res.statusCode = 200;  
  res.end('Hello from Node.js!');  
});  
server.listen(port, hostname, () => {  
  console.log(`Server running at http://${hostname}:${port}/`);  
});  
Express简化了服务器配置,示例代码:
const express = require('express');  
const app = express();  
const port = 3000;  
app.get('/', (req, res) => {  
  res.send('Hello from Express!');  
});  
app.listen(port, () => {  
  console.log(`Express server running on port ${port}`);  
});  
若需绑定特定IP,可在app.listen()中添加参数:
app.listen(port, '0.0.0.0', () => { // '0.0.0.0'表示监听所有网络接口  
  console.log(`Server accessible on all interfaces`);  
});  
若需HTTPS,可使用https模块并指定证书文件:
const https = require('https');  
const fs = require('fs');  
const options = {  
  key: fs.readFileSync('path/to/private-key.pem'),  
  cert: fs.readFileSync('path/to/certificate.pem')  
};  
https.createServer(options, (req, res) => {  
  res.writeHead(200);  
  res.end('Secure connection!');  
}).listen(443, '0.0.0.0');  
sudo apt install nginx  
/etc/nginx/sites-available/default,添加反向代理规则:server {  
  listen 80;  
  server_name your_domain.com;  
  location / {  
    proxy_pass http://localhost:3000; // 转发到Node.js应用  
    proxy_set_header Host $host;  
    proxy_set_header X-Real-IP $remote_addr;  
  }  
}  
sudo systemctl restart nginx  
访问http://your_domain.com即可通过Nginx代理Node.js服务。
process.env.PORT)管理IP和端口,避免硬编码。以上步骤参考自,可根据实际需求选择配置方式。