From the output of the ps aux | grep node command, it looks like the Node.js process is running as the root user. This means you need to ensure that the root user has the appropriate permissions to write to the directory where you want to save files.
Steps to Set Up Directory Permissions
Create the Directory for Images
If you haven’t already created the directory for images, you can do so with the following command:
bashsudo mkdir -p /var/www/imagesSet Ownership to Root
Since your Node.js process runs as the
rootuser, you can set the ownership of the directory toroot:bashsudo chown -R root:root /var/www/imagesSet Permissions
Set the permissions to allow reading, writing, and executing for the owner (root) and reading and executing for others:
bashsudo chmod -R 755 /var/www/images
Summary of Commands
Create the Directory
bashsudo mkdir -p /var/www/imagesChange Ownership
bashsudo chown -R root:root /var/www/imagesSet Permissions
bashsudo chmod -R 755 /var/www/images
Considerations for Production
Running Node.js processes as the root user is not recommended for production environments due to security risks. It’s better to run your Node.js application under a dedicated user account with limited permissions. If you plan to move to a more secure setup, consider creating a separate user for your application.
To create a new user and run your Node.js process under that user:
Create a New User
bashsudo adduser nodeappChange Ownership of the Directory
bashsudo chown -R nodeapp:nodeapp /var/www/imagesUpdate Your Application to Run as the New User
You would need to update the startup scripts or process manager configuration to run the application under the
nodeappuser. For example, if usingpm2, you can set the user in theecosystem.config.jsfile or thepm2start command.
Example Using pm2
If you are using pm2 to manage your application, you can start the application under a different user:
Install
pm2(if not already installed)bashsudo npm install -g pm2Start Your Application with
pm2bashpm2 start index.js --name "my-app" --user nodeapp
This way, the nodeapp user will run your Node.js process, and you can manage permissions and security more effectively.