Switching from root to non-root user in Docker entrypoint script for .NET 8

366 Views Asked by At

I am working on a Dockerfile for a .NET 8 application, and I have an entrypoint script that needs to perform some tasks as the root user before switching to a non-root user for starting the application. The Dockerfile and entrypoint script structure is as follows:

FROM mcr.microsoft.com/dotnet/aspnet:8.0.0-alpine3.18-amd64 AS final

WORKDIR /app
RUN apk add --no-cache tini=0.19.0-r1 su-exec=0.2-r3

COPY entrypoint.sh /
RUN chmod 755 /entrypoint.sh

ENTRYPOINT ["/sbin/tini", "--", "/entrypoint.sh"]
COPY --from=publish /app .

and the entrypoint script is

#!/usr/bin/env sh

# ... tasks running as root ...

exec su-exec app:app dotnet server.dll

In this setup, I expect the entrypoint script to run tasks as root initially and then switch to the non-root user (app:app) when executing the .NET application. However, when I exec into the container and check the user using whoami, I still see that I am on the root user.

For reference, in .NET 7, the same setup worked as expected although in this version I needed to create the user myself so my dockerfile was

FROM mcr.microsoft.com/dotnet/aspnet:7.0.10-alpine3.17-amd64 AS final

# creating my own non-root user
RUN addgroup --gid 1000 -S app && adduser --uid 1000 -S app -G app

WORKDIR /app
RUN apk add --no-cache tini=0.19.0-r1 su-exec=0.2-r2

COPY entrypoint.sh /
RUN chmod 755 /entrypoint.sh

ENTRYPOINT ["/sbin/tini", "--", "/entrypoint.sh"]
COPY --from=publish /app .
1

There are 1 best solutions below

1
Joe Gurria Celimendiz On

I use the following commands placed after the first FROM statement to run as non-root user with .Net 6.0 in the Dockerfile.

   ARG USERNAME=non-root-user
   ARG USER_UID=1000
   ARG USER_GID=$USER_UID

   # Create the user
   RUN groupadd --gid "$USER_GID" "$USERNAME" \
     && useradd --uid "$USER_UID" --gid "$USER_GID" -m "$USERNAME" \
     #
   # [Optional] Add sudo support. Omit if you don't need to install 
   software after connecting.
     && apt-get update \
     && apt-get install --no-install-recommends -y sudo \
     && echo "$USERNAME" ALL=\(root\) NOPASSWD:ALL > 
     /etc/sudoers.d/"$USERNAME" \
     && chmod 0440 /etc/sudoers.d/"$USERNAME" \
     && apt-get clean

Then before commands in the Dockerfile that require a non-root user place the following command.

 USER $USERNAME
 #for example the following
 FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
 ...

This Dockerfile also worked with a .Net 8.0 Visual Studio solution.

Hope it helps!