在Linux上部署JavaScript代码通常涉及以下几个步骤:
准备环境:
sudo apt update
sudo apt install nodejs npm
上传代码:
scp -r /path/to/your/local/project username@remote_host:/path/to/remote/directory
安装依赖:
cd /path/to/remote/directory
npm install
配置服务器:
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(`Server running at http://localhost:${port}/`);
});
启动应用:
node app.js
使用进程管理器(可选但推荐):
npm install pm2 -g
pm2 start app.js --name my-app
配置反向代理(可选):
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;
}
}
/etc/nginx/sites-available/your_domain.com
,然后创建符号链接到sites-enabled
目录:sudo ln -s /etc/nginx/sites-available/your_domain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
安全配置:
通过以上步骤,你应该能够在Linux上成功部署你的JavaScript代码。