Query about adding user in dockerfile for dockerizing the simple react app

Viewed 141

I am stuck this issue: when I add the user in Dockerfile at the end and build an image from it and after that when I start a container from this image, I have permission denied errors. I start the container using this command:

docker run react-app npm start

It gives the permission denied error because I created build as a root user and defined the new "app" user at the end. When I moved the new "app" user at the top then the permission denied error happens while building the image. Here is the my Dockerfile before and after I make this change:

Before

FROM node:14.16.1-alpine3.13
WORKDIR /app/
COPY package*.json .
RUN npm install
COPY . .
ENV API_URL=https://api.myapp.com
EXPOSE 3000
RUN addgroup app && adduser -S -G app app
USER app

Creating image from it, image tagged react-app. The error after running the image is:

$ docker run react-app npm start
:information_source: 「wds」: Project is running at http://172.17.0.2/
:information_source: 「wds」: webpack output is served from
:information_source: 「wds」: Content not from webpack is served from /app/public
:information_source: 「wds」: 404s will fallback to /
Starting the development server…
Failed to compile.
EACCES: permission denied, mkdir ‘/app/node_modules/.cache’

After

FROM node:14.16.1-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app/
COPY package*.json .
RUN npm install
COPY . .
ENV API_URL=https://api.myapp.com
EXPOSE 3000

error while building the image after running the image:

$ docker build -t react-app

npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /app
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access ‘/app’
npm ERR! [Error: EACCES: permission denied, access ‘/app’] {
npm ERR! errno: -13,
npm ERR! code: ‘EACCES’,
npm ERR! syscall: ‘access’,
npm ERR! path: ‘/app’
npm ERR! }

How can I resolve this issue?

1 Answers

I have once had a similar problem. I found a solution that I believe is also appliable to this scenario. I don't know if they are against any best practices,but the solution worked for me. Basicaly I've changed the ownership of the unaccessible files to belong to the user that was executing the processes in the container.

In your case, the dockerfiles would as follows:

FROM node:14.16.1-alpine3.13
WORKDIR /app/
COPY package*.json .
RUN npm install
COPY . .
RUN chown -R app /app/node_modules
ENV API_URL=https://api.myapp.com
EXPOSE 3000
RUN addgroup app && adduser -S -G app app
USER app

As for building the app inside the container, I believe you will have to make all the files from folder /app/ accessible to user app, it would then be as follows:

FROM node:14.16.1-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app/
COPY package*.json .
RUN npm install
COPY . .
RUN chown -R app /app
ENV API_URL=https://api.myapp.com
EXPOSE 3000
Related