对于 Ubuntu/Debian:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
对于 CentOS/RHEL:
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo yum install -y nodejs
# 下载 Node.js
wget https://nodejs.org/dist/v18.16.0/node-v18.16.0-linux-x64.tar.xz
# 解压
tar -xvf node-v18.16.0-linux-x64.tar.xz
# 移动到合适位置
sudo mv node-v18.16.0-linux-x64 /usr/local/nodejs
# 添加到 PATH
echo 'export PATH=$PATH:/usr/local/nodejs/bin' >> ~/.bashrc
source ~/.bashrc
node -v
npm -v
创建项目目录:
mkdir ~/helloworld
cd ~/helloworld
创建 app.js
文件:
nano app.js
输入以下内容:
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World from Node.js!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
直接运行:
node app.js
测试访问:
curl http://localhost:3000
安装 PM2:
npm install -g pm2
启动应用:
pm2 start app.js
设置开机启动:
pm2 startup
pm2 save
创建服务文件:
sudo nano /etc/systemd/system/nodeapp.service
添加以下内容:
[Unit]
Description=Node.js Hello World App
After=network.target
[Service]
ExecStart=/usr/bin/node /home/yourusername/helloworld/app.js
WorkingDirectory=/home/yourusername/helloworld
User=yourusername
Restart=always
[Install]
WantedBy=multi-user.target
启用并启动服务:
sudo systemctl daemon-reload
sudo systemctl enable nodeapp
sudo systemctl start nodeapp
sudo ufw allow 3000/tcp
在浏览器中访问:http://your-server-ip:3000
你应该能看到 "Hello World from Node.js!" 的消息。
app.js
中的端口号希望这个指南能帮助你在 Linux 上成功部署 Node.js 的 Hello World 应用!