插件窝 干货文章 nodejs怎么部署到linux上跑出hello world

nodejs怎么部署到linux上跑出hello world

bash Node sudo 应用 842    来源:    2025-04-22

Node.js 在 Linux 上部署 Hello World 指南

准备工作

  1. 确保你有一台运行 Linux 的服务器或虚拟机
  2. 拥有 SSH 访问权限

部署步骤

1. 安装 Node.js

方法一:使用包管理器(推荐)

对于 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

2. 验证安装

node -v
npm -v

3. 创建 Hello World 应用

创建项目目录:

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}/`);
});

4. 运行应用

直接运行:

node app.js

测试访问:

curl http://localhost:3000

5. 保持应用运行(可选)

使用 PM2(推荐)

安装 PM2:

npm install -g pm2

启动应用:

pm2 start app.js

设置开机启动:

pm2 startup
pm2 save

使用 systemd

创建服务文件:

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

6. 防火墙设置(如果需要外部访问)

sudo ufw allow 3000/tcp

访问应用

在浏览器中访问:http://your-server-ip:3000

你应该能看到 "Hello World from Node.js!" 的消息。

常见问题解决

  1. 端口被占用:修改 app.js 中的端口号
  2. 权限问题:确保 Node.js 有权限访问项目目录
  3. EADDRINUSE:检查是否有其他进程占用了相同端口
  4. 连接被拒绝:检查防火墙设置和服务器安全组规则

希望这个指南能帮助你在 Linux 上成功部署 Node.js 的 Hello World 应用!