brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: COPY with chown sets file owners in a Dockerfile without an extra layer

Docker
~/tips/tip-dockerfile-copy-chown

COPY --chown=app:app . .

Give copied files to the app user in the same step that copies them.

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

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link