插件窝 干货文章 ubuntu下安装nodejs并实现Nginx反向代理服务器的方法

ubuntu下安装nodejs并实现Nginx反向代理服务器的方法

bash Nginx 安装 sudo 603    来源:    2025-04-24

Ubuntu下安装Node.js并配置Nginx反向代理

1. 安装Node.js

方法一:使用Ubuntu官方仓库安装

sudo apt update
sudo apt install nodejs npm

安装完成后验证版本:

node -v
npm -v

方法二:使用NodeSource仓库安装最新版本

  1. 添加NodeSource仓库:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
  1. 安装Node.js和npm:
sudo apt-get install -y nodejs

方法三:使用nvm(Node Version Manager)安装

  1. 安装nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
  1. 重新加载shell配置:
source ~/.bashrc
  1. 安装Node.js:
nvm install --lts
nvm use --lts

2. 创建Node.js应用

  1. 创建一个简单的Express应用:
mkdir myapp && cd myapp
npm init -y
npm install express
  1. 创建app.js文件:
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
  1. 测试应用:
node app.js

访问http://localhost:3000确认应用正常运行

3. 使用PM2管理Node.js进程

  1. 全局安装PM2:
sudo npm install -g pm2
  1. 使用PM2启动应用:
pm2 start app.js --name "myapp"
  1. 设置开机启动:
pm2 startup
pm2 save

4. 安装和配置Nginx

  1. 安装Nginx:
sudo apt install nginx
  1. 启动Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
  1. 配置Nginx反向代理: 创建新的配置文件:
sudo nano /etc/nginx/sites-available/myapp

添加以下内容(替换your_domain.com为你的域名或服务器IP):

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;
    }
}
  1. 启用配置:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled
  1. 测试Nginx配置:
sudo nginx -t
  1. 重启Nginx:
sudo systemctl restart nginx

5. 配置防火墙(可选)

如果使用UFW防火墙:

sudo ufw allow 'Nginx Full'
sudo ufw allow ssh
sudo ufw enable

6. 验证配置

访问你的服务器IP或域名,应该能看到Node.js应用的内容。

7. 可选:配置HTTPS(使用Let's Encrypt)

  1. 安装Certbot:
sudo apt install certbot python3-certbot-nginx
  1. 获取SSL证书:
sudo certbot --nginx -d your_domain.com
  1. 设置自动续期:
sudo certbot renew --dry-run

现在你的Node.js应用已经通过Nginx反向代理安全地提供服务了。