Node.js在Debian中的网络配置分为系统网络配置和Node.js应用网络配置两部分,具体如下:
通过编辑网络配置文件设置IP地址、网关、DNS等,适用于静态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
在应用代码中指定监听的IP地址和端口,无需额外配置系统网络。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
const ipAddress = '127.0.0.1'; // 监听本地地址
const port = 3000;
server.listen(port, ipAddress, () => {
console.log(`Server running at http://${ipAddress}:${port}/`);
});
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
sudo apt install nginx
/etc/nginx/sites-available/default,添加以下内容:server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
sudo systemctl restart nginx
netplan或NetworkManager替代传统/etc/network/interfaces。https模块并指定证书文件。ufw或iptables开放应用端口(如HTTP的80端口、HTTPS的443端口)。