Files added with COPY belong to root. The common fix, a RUN chown -R afterwards, copies every file into a second layer and can double the size of that part of the image. COPY --chown sets the owner in one go.
FROM node:22-alpine
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app
COPY --chown=app:app . .
USER app
CMD ["node", "server.js"]
The files land in the image already owned by app, so the process that runs as app can write where it needs to. There is a matching --chmod for permissions, such as --chmod=755 for a script.
Names are looked up in the image’s /etc/passwd and /etc/group, so the user has to be created before the COPY line. In images without those files, such as scratch, use numbers: --chown=1000:1000.
I would not give the app user ownership of its own code unless it really has to write there. Owned by root and readable by everyone is safer, because a bug in the app then cannot rewrite the app. Keep --chown for the folders the app writes to, like a cache or upload directory. The flag only works on Linux containers.
Further reading: Dockerfile reference: COPY –chown