If I start my express project with pm2, my static files in 'public' directory will become inaccessible.
After some time, I figured out that I had multiple projects with the same 'app.js' file as startup js.
So if I use pm2 to start all these app.js, all the app name should be 'app', though with different ids,
I suspect pm2 can't distinguish these projects with same names, because after I changed the app.js to different names, everything went ok
If you do pm2 delete app.js to remove the process from pm2 list, and then pm2 start app.js will solve it too without file renaming. I guess there is some cache persistent between stop and restart/start actions and it messed up somehow.
I hit this as well, but at least for me, the issue was specifying an incorrect relative path for Express' static files.
In my server, I was serving static files with:
app.use(express.static('public'));
At first, this looks correct. However, this actually directs Express to serve static files out of the public folder that is _relative to the working directory_.
I was running pm2 start /srv/www/project/server.js from a startup script through Docker, so the working directory was /. The static files were being served out of /public instead of the expected /srv/www/project/public.
Deleting and restarting worked for me, too, but that was because I cd'd to /srv/www/project before running pm2 start server.js. With a working directory of /srv/www/project, everything worked.
In the end, the fix is simple. Use __dirname to ensure the static files are served relative to the script, not the current working directory:
app.use(express.static(__dirname + '/public'));
Express' documentation explains this as well.
@schmich Thank you for posting your update, even after the issue was closed, I had the exact same problem and your solution works great!
Most helpful comment
I hit this as well, but at least for me, the issue was specifying an incorrect relative path for Express' static files.
In my server, I was serving static files with:
At first, this looks correct. However, this actually directs Express to serve static files out of the
publicfolder that is _relative to the working directory_.I was running
pm2 start /srv/www/project/server.jsfrom a startup script through Docker, so the working directory was/. The static files were being served out of/publicinstead of the expected/srv/www/project/public.Deleting and restarting worked for me, too, but that was because I
cd'd to/srv/www/projectbefore runningpm2 start server.js. With a working directory of/srv/www/project, everything worked.In the end, the fix is simple. Use
__dirnameto ensure the static files are served relative to the script, not the current working directory:Express' documentation explains this as well.