I am trying to expand my skill set to include react/nextjs/yarn:
I notice that most of the examples have you install everything to run as root, but that most people recommend running the app as an application user so that the application does not own its own code (this makes sense to me)
When installing as root with Dockerfile and using pnp, yarn install installs all the dependencies in root’s home directory and hard codes the paths in.pnp.cjs and .pnp.loader.mjs .
package.json has (among other things):
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
Running the server as root with eg:
CMD ["yarn", "dev"]
runs the server as expected.
However if we do:
USER app_user
CMD ["yarn","dev"]
It reads the path to next from .pnp.loader.mjs and fails of permission errors because it’s trying to access and update root’s yarn environment
Eg: Error: Required package exists but could not be accessed (eACCES: permission denied, access '/root/.yarn/berry/cache/next-npm-14.2.5-ce63d89d89-10c0.zip/node_modules/next/').
...ommitted stuff ..
Missing package: next@virtual:10d0ddd8962b160e8b7988b5b1cf9ce26b9a58b41ec7af94ce9595f61af7631df76c6dd2f22bd9f3088af482b8c60bcf3382616263c556f0e3ba392e203ea268#npm:14.2.5
Expected package location: /usr/local/app/.yarn/__virtual__/next-virtual-86a0c6e4d9/4/root/.yarn/berry/cache/next-npm-14.2.5-ce63d89d89-10c0.zip/node_modules/next/
Here is the listing showing the .yarn directory in /usr/local/app
drwxr-xr-x 3 root root 4096 Aug 5 19:29 .yarn
Ok it makes sense we got that error, since we don’t want to update or access the unzipped modules root owns if our purpose is to not have the app own its code.
So apparently the app_user needs access to this directory. I suppose I could start changing permissions, but since this would give the app_user permissions to update the code it’s actually running, I may as well just install everything as the app_user to be sure I’ve gotten everything needed.
So I update my Dockerfile like so:
... stuff omitted
# Have to switch to this user or path to root owned cache is used by
# yarn pnp creating permission errs
ENV SERVICE_NAME=app_user
USER $SERVICE_NAME
RUN mkdir -p ~/bin
RUN corepack enable --install-directory ~/bin
COPY demo/.yarnrc.yml ./
... rest omitted
Here I’m doing the whole install as the user $SERVICE_NAME and not just switching to that user after install before running the app.
This means the code is owned by that app user, which would mean that user could update the code if it were hacked somehow. It’s better than running as root since only the app’s code could be altered, but it seems less than ideal to me.
I wanted to know what is the correct way of running the app as a non-root user.
Thanks.
user26649612 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.