sudo apt update
sudo apt install nodejs npm
安装完成后验证版本:
node -v
npm -v
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts
mkdir myapp && cd myapp
npm init -y
npm install express
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}`)
})
node app.js
访问http://localhost:3000
确认应用正常运行
sudo npm install -g pm2
pm2 start app.js --name "myapp"
pm2 startup
pm2 save
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable 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;
}
}
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
如果使用UFW防火墙:
sudo ufw allow 'Nginx Full'
sudo ufw allow ssh
sudo ufw enable
访问你的服务器IP或域名,应该能看到Node.js应用的内容。
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com
sudo certbot renew --dry-run
现在你的Node.js应用已经通过Nginx反向代理安全地提供服务了。