【问题标题】:How to run .NET Core 2 application in Docker on Linux as non-root如何在 Linux 上的 Docker 中以非 root 用户身份运行 .NET Core 2 应用程序
【发布时间】:2018-11-29 17:24:51
【问题描述】:

我在 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 1000
ENTRYPOINT ["dotnet", "ConfigApi.dll"]

这是我运行生成的图像时出现的 Kestral 错误。

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

有人解决了吗?

【问题讨论】:

  • 你绑定到 Kestrel 的哪个端口?
  • 此时仅端口 80。如果我省略 USER customuser 行,这运行正常。

标签: docker .net-core dockerfile


【解决方案1】:

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

【讨论】:

  • 如果我想在不同容器中运行的数据库上执行迁移(从这个应用程序内部),这可能吗?
  • @marrrschine 当然,只要您的应用程序连接到数据库,数据库在哪里都没有关系
【解决方案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】:

有没有人解决这个问题。我已经厌倦了使用端口 5000 并且仍然无法使用自定义用户进行此操作

【讨论】:

  • 是的,您可能缺少的一点是,当您在文件末尾指定要使用的用户时,您必须使用用户号。 IE。 USER 5000 Entrypoint . . .
【解决方案4】:

为了使 ASP.NET 核心能够绑定到更高的端口,我在我的 dockerfile 中设置了这个环境变量

ENV ASPNETCORE_URLS=http://*:8080

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

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2016-04-11
    • 2022-01-15
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多