如何以非超级用户身份在Linux上的Docker中运行.NET Core 2应用程序

时间:2018-11-29 17:24:51

标签: docker .net-core dockerfile

我已经在docker中成功运行了一个简单的dotnet core 2.1 Web API应用程序,但是我想在自定义帐户下而不是root下运行它,因为这是最佳做法。

我可以添加一个帐户并更改为该帐户,但是Kestral会在启动时引发错误。

我反复在网上搜索,找不到任何解决方案。

这是Docker文件。

FROM sel-docker.artifactory.metro.ad.selinc.com/microsoft/dotnet:2.1.500-sdk-    
alpine3.7 AS build-env
WORKDIR /app

# copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# build runtime image
FROM sel-docker.artifactory.metro.ad.selinc.com/microsoft/dotnet:2.1.6- 
aspnetcore-runtime-alpine3.7

# Create a group and user
RUN addgroup -S -g 1000 customgroup \
&& adduser -S -u 1000 -G customgroup -s /bin/sh customuser

WORKDIR /app
RUN mkdir -p /local/
COPY --from=build-env /app/out .

RUN chown customuser:customgroup /local
RUN chown customuser:customgroup /app

# Tell docker that all future commands should run as the appuser user
USER customuser
ENTRYPOINT ["dotnet", "ConfigApi.dll"]

这是我运行结果图像时的Kestral错误。

crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
System.Net.Sockets.SocketException (13): Permission denied
...

有人解决了吗?

4 个答案:

答案 0 :(得分:3)

在linux中,绑定到小于1024的端口要求用户是超级用户。您可以只使用默认端口5000,然后将其发布到主机上的端口80(如果您没有任何反向代理)。

答案 1 :(得分:2)

要使ASP.NET Core绑定到更高的端口,我在dockerfile中设置了此环境变量

ENV ASPNETCORE_URLS=http://*:8080

来源:https://github.com/dotnet/aspnetcore/issues/4699#issuecomment-454818058

答案 2 :(得分:2)

因为这会带来大量流量,所以我添加了完成此操作所需的完整代码。

# Create a group and user so we are not running our container and application as root and thus user 0 which is a security issue.
RUN addgroup --system --gid 1000 customgroup \
    && adduser --system --uid 1000 --ingroup customgroup --shell /bin/sh customuser
  
# Serve on port 8080, we cannot serve on port 80 with a custom user that is not root.
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
  
# Tell docker that all future commands should run as the appuser user, must use the user number
USER 1000

答案 3 :(得分:0)

有人能做到这一点吗?我也对使用端口5000感到厌倦,但仍然无法与自定义用户一起使用