Node.js在Debian上的网络配置分为系统网络配置和Node.js应用网络配置两部分,具体步骤如下:
通过编辑网络接口文件设置IP、网关、DNS等基础网络参数。
编辑网络配置文件
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
(将eth0替换为实际网卡名,如ens33)auto eth0
iface eth0 inet dhcp
重启网络服务
sudo systemctl restart networking
(若使用NetworkManager,可执行sudo systemctl restart NetworkManager)
验证网络连通性
ping www.google.com
若能ping通,则网络配置成功。
在Node.js代码中指定监听的IP和端口,或通过框架简化配置。
原生HTTP模块配置
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
// 监听指定IP和端口(IP可设为'0.0.0.0'以监听所有接口)
server.listen(3000, '0.0.0.0', () => {
console.log('Server running at http://0.0.0.0:3000/');
});
使用Express框架配置
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port, '0.0.0.0', () => {
console.log(`Server running at http://0.0.0.0:${port}/`);
});
配置HTTPS(可选)
需指定SSL证书路径:
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.end('Secure Hello World');
}).listen(443, '0.0.0.0');
安装Nginx
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;
}
}
重启Nginx
sudo systemctl restart nginx
/etc/netplan/*.yaml配置网络,需通过netplan apply应用更改。sudo ufw allow 3000/tcp # 允许Node.js应用端口
以上配置可根据实际需求调整IP、端口及代理设置,确保Node.js应用能正常访问。