在Linux服务器上部署Node.js应用通常涉及以下几个步骤:
准备工作:
# 使用NodeSource二进制分发库安装Node.js
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
上传应用代码:
安装依赖:
cd /path/to/your/nodejs-app
npm install
配置环境变量(如果有必要):
~/.bashrc
或~/.bash_profile
文件中添加:export NODE_ENV=production
export PORT=3000
source ~/.bashrc
或source ~/.bash_profile
使变量生效。启动应用:
node app.js
app.js
是你的主应用文件。使用进程管理器(推荐):
sudo npm install pm2 -g
pm2 start app.js --name "your-app-name"
配置Nginx反向代理(可选):
sudo apt-get install nginx
/etc/nginx/sites-available/default
),添加以下内容:server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl restart nginx
设置防火墙规则(可选):
sudo ufw allow 3000
通过以上步骤,你应该能够在Linux服务器上成功部署你的Node.js应用。