Docker > Building Images > Lectures 11 & 12 > User Permissions

This issue of moving the user creation to the top of the Dockerfile (first 2 minutes of lecture 12) has confused me.

I get that root user did the previous steps and has write permission where app user does not - so I can see that running npm start throws an error because the app user cannot write this .cache.

So now I presume that moving app user creation to the top solves the issue because now the app user is owner of everything that got copied and so has write permission within it.

But if that’s correct, doesn’t it invalidate what Mosh said at the very end of the lecture 11 about how changing the user at the end was good because otherwise a hacker can potentially make changes to the code?

1 Like

Hi,
Since you didn’t create the directories through the RUN instruction which runs a linux command using the user you’re logged-on with, the WORKDIR will be created by the root user and so is the other directories docker copied.

You can check it out.
Just run the container using the -it flag and using sh for shell
docker run -it yourContainerName sh

Then run the command “ls -l” when you’re in the right directory.
You’ll see all folders and files were created by the root user, while node_modules was created by your user.
If you want, add another RUN instruction with “mkdir some-test-dir” and re-build your image.
Do the same trick - run for creating the container and ls -l in the directory and you’ll see that some-test-dir was created by the user you defined too.

1 Like

This confused me as well.

Here’s how I decided to create a non-root user and gave permission to only runtime files/folders.

FROM node:20.10.0-alpine3.19

# React app lives here
WORKDIR /app

# Set environment variables
ENV TEST="Hello Docker!"

# Install application packages
COPY package*.json .
RUN npm install

# Copy application code
COPY . .

# Add a non-root user
RUN addgroup app && \
    adduser -S -G app app

# Run and own only the runtime files as a non-root user for security
RUN mkdir node_modules/.cache && \
    chown app:app node_modules/.cache

# Switch to non-root user
USER app

# Start the server by default, this can be overwritten at runtime
EXPOSE 3000
CMD ["npm", "start"]