iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖
Running Distroless Images as a Non-root User
In this article, I explored how to run a container as a non-root user when using Distroless.
Conclusion
Use COPY --chown=nonroot:nonroot and USER nonroot.
Dockerfile
FROM gcr.io/distroless/nodejs:14
WORKDIR /app
COPY --chown=nonroot:nonroot --from=build /app /app
USER nonroot
EXPOSE 3000
CMD ["dist/main"]
Node.js Dockerfile
Dockerfile
#==================================================
# Build Layer
FROM node:14-slim as build
WORKDIR /app
COPY package.json yarn.lock ./
COPY . .
RUN yarn install --non-interactive --frozen-lockfile
RUN yarn build
#==================================================
# Package install Layer
FROM node:14-slim as node_modules
WORKDIR /app
COPY package.json yarn.lock ./
COPY . .
RUN yarn install --non-interactive --frozen-lockfile --prod
#==================================================
# Run Layer
FROM gcr.io/distroless/nodejs:14
WORKDIR /app
COPY --chown=nonroot:nonroot --from=build /app/dist /app/dist
COPY --chown=nonroot:nonroot --from=node_modules /app/node_modules /app/node_modules
USER nonroot
EXPOSE 3001
CMD ["dist/main"]
Handling non-root users in Distroless
In typical Docker images, you would create a user with adduser or similar commands because a shell is included.
When I tried to do the same in Distroless, an error occurred because there is no shell to execute the command.
> [stage-2 2/6] RUN groupadd -r app && useradd -r -g app -G app:
#6 0.332 container_linux.go:370: starting container process caused: exec: "/bin/sh": stat /bin/sh: no such file or directory
Upon researching how to do this, it seems that a user and group named nonroot have already been created.
I used gcr.io/distroless/nodejs:debug to confirm if it becomes nonroot.
$ whoami
nonroot
$ ls -l
drwxr-xr-x 2 nonroot nonroot 4096 Mar 18 16:08 dist
drwxr-xr-x 3 nonroot nonroot 4096 Mar 18 16:08 node_modules
It was indeed nonroot without any issues.
Next, I checked the users and groups present in Distroless.
$ cat /etc/passwd
root:x:0:0:root:/root:/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/sbin/nologin
nonroot:x:65532:65532:nonroot:/home/nonroot:/sbin/nologin
$ cat /etc/group
root:x:0:
nobody:x:65534:
tty:x:5:
staff:x:50:
nonroot:x:65532:
These users and groups seem to be included by default.
Discussion