You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Linux Mint上部署Node.js应用实现后台常驻及开机自启?

Node.js按键监控应用后台常驻+开机自启部署方案(结合Apache/Nginx)

一、用PM2实现后台常驻与开机自启

既然你不想用Linux原生服务,PM2是Node.js生态中最适合的进程管理器,能直接解决后台运行和开机自启问题:

  • 全局安装PM2:
    npm install pm2 -g
    
  • 启动你的应用(替换为实际路径):
    pm2 start /path/to/your/app.js --name "key-monitor"
    
  • 设置开机自启:
    pm2 startup
    
    执行终端输出的系统命令完成配置,比如Debian/Ubuntu下会生成systemctl enable pm2-root这类命令。
  • 保存当前PM2进程列表,确保重启后自动恢复:
    pm2 save
    

二、Apache反向代理配置(若应用有HTTP接口)

如果你的Node.js应用提供HTTP接口,可通过Apache反向代理对外暴露:

  1. 确认proxy模块已启用(你之前操作过,再次验证):
    a2enmod proxy proxy_http
    systemctl restart apache2
    
  2. 创建虚拟主机配置文件(比如/etc/apache2/sites-available/key-monitor.conf):
    <VirtualHost *:80>
        ServerName your-server-ip # 替换为你的服务器IP或域名
    
        ProxyPreserveHost On
        ProxyPass / http://localhost:3000/  # 替换为你的Node应用监听端口
        ProxyPassReverse / http://localhost:3000/
    
        ErrorLog ${APACHE_LOG_DIR}/key-monitor-error.log
        CustomLog ${APACHE_LOG_DIR}/key-monitor-access.log combined
    </VirtualHost>
    
  3. 启用配置并重启Apache:
    a2ensite key-monitor.conf
    systemctl restart apache2
    

三、Nginx反向代理配置(若应用有HTTP接口)

若使用Nginx,配置步骤如下:

  1. 创建虚拟主机配置文件(比如/etc/nginx/sites-available/key-monitor.conf):
    server {
        listen 80;
        server_name your-server-ip; # 替换为你的服务器IP或域名
    
        location / {
            proxy_pass http://localhost:3000; # 替换为你的Node应用监听端口
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    
        error_log /var/log/nginx/key-monitor-error.log;
        access_log /var/log/nginx/key-monitor-access.log;
    }
    
  2. 启用配置并重启Nginx:
    ln -s /etc/nginx/sites-available/key-monitor.conf /etc/nginx/sites-enabled/
    nginx -t # 验证配置语法
    systemctl restart nginx
    

关键注意事项

  • 确保Node应用监听的端口未被其他服务占用,可通过netstat -tulpn | grep 3000(替换为你的端口)检查。
  • iohook需要系统级权限,若PM2启动后无法正常监控按键,可尝试用sudo pm2 start ...启动(建议后续调整应用权限,避免长期用root运行)。
  • 如果你的应用没有HTTP接口,仅需PM2即可实现后台常驻和开机自启,Web服务器反向代理并非必需——这部分是为了对外暴露应用的HTTP服务而配置的。

内容的提问来源于stack exchange,提问作者Stupid Questions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:41:19