FROM node:14.16.0-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package*.json ./
RUN npm install
COPY . .
ENV APP_URL=http://api.myapp.com
EXPOSE 3000
CMD ["npm", "start"]
This is my docker file. I am trying to dockerize a sample react-app. I added user in group and then using that user for further commands as you can see this in second line of this code. I believe by default, only root user has access to write to these files and in order to do changes in these files, root user should not be user. Hence I created app user here.
But after running docker build -t react-app.. I am getting the following error -
What am I doing wrong here? Any suggestions?
You are seeing this error because /app directory belongs to root user. The user app which you created has no write permission to this directory. User app needs write permission to install node packages (create node_modules directory and package-lock.json file).
As suggested by @DavidMaze in comments, it would be easy to do package installation as root user and switch to USER app at the last but before the runtime CMD ["npm", "start"].
But still app user would need write permission to node_modules/.cache directory when running the app with npm start command. Hence, we need to provide the write permission to user app for this directory.
Here is an example that does all mentioned above:
FROM node:14.16.0-alpine3.13
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package*.json ./
RUN npm install
COPY . .
ENV APP_URL=http://api.myapp.com
EXPOSE 3000
RUN addgroup app && adduser -S -G app app
RUN mkdir node_modules/.cache
RUN chown app:app node_modules/.cache
USER app
CMD ["npm", "start"]
Also, note that you are running the React App in development mode using npm start, you might want to use a static server to serve, after creating a build.
when you create user with name "app", a new directory for this user is created in home directory "/home/app" so,workdir should be like this:
WORKDIR /home/app