Ubuntu 16.04 下 Node.js 项目是否应存于网站文档根目录?
Is Storing Node.js Projects in /var/www/html/ Recommended?
Great question! Let’s break down whether putting your Node.js app in /var/www/html/ makes sense, plus cover better storage options for production.
Should You Use /var/www/html/?
Short answer: It’s not recommended for production Node.js apps, and here’s why:
- Permission Conflicts:
/var/www/html/is owned by thewww-datauser/group (Apache’s default user). If your Node.js app runs under a different user (like a dedicatednodeuser for security), you’ll run into read/write permission issues for project files, dependencies, or logs. - Confused Responsibilities: This directory is designed for Apache’s static web content (like HTML/CSS/PHP files). Mixing a Node.js backend service here blurs lines between static assets and server-side code, making deployment, backups, and maintenance messier.
- Security Risks: If your Node app includes sensitive config files (like
.envwith API keys), storing them in Apache’s web root could expose them publicly if your Apache config is misconfigured—big no-no for production.
Recommended Storage Locations for Node.js Apps
Here are the best options, depending on your use case:
- /opt/your-app-name/: This directory is intended for optional third-party applications, making it perfect for Node.js projects. You can set strict permissions here, separate from Apache’s web root, and keep your app isolated.
- /srv/your-app-name/: Semantically, this is for "service data"—ideal for backend apps that provide a service (like your Node.js API). It’s a standard location for production services on Linux systems.
- /home/your-user/projects/your-app/: If you’re working in a non-production environment (like a dev server or personal setup), storing projects in your user directory is fine. It’s easy to manage, just make sure to lock down permissions if you ever move to production.
Quick Best Practices
- Use a Dedicated User: Create a
nodeuser to run your Node.js process instead of root orwww-data—this limits damage if your app is compromised. Set ownership of your project directory to this user withsudo chown -R node:node /path/to/your/app. - Apache Reverse Proxy: Since Node.js runs on its own port, configure Apache to reverse proxy requests to that port. This way, your app doesn’t need to live in
/var/www/html/at all—Apache just forwards traffic to your Node service. - Process Management: Use a tool like
pm2to manage your Node.js process. It will keep your app running, restart it on crashes, and let you easily specify your project’s directory regardless of where it’s stored.
内容的提问来源于stack exchange,提问作者Philipp M
相关产品推荐
相关产品推荐

