如何在 Linux 上的 Docker 中以非 root 用户身份运行 .NET Core 2 应用程序 [英] How to run .NET Core 2 application in Docker on Linux as non-root

查看:34
本文介绍了如何在 Linux 上的 Docker 中以非 root 用户身份运行 .NET Core 2 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm successfully running a simple dotnet core 2.1 web API application in docker but want to run it under a custom account instead of under root as this is supposedly best practice.

我可以添加一个帐户并更改为该帐户,但随后 Kestral 在启动时抛出错误.

I can add an account and change to that account, but then Kestral throws an error on startup.

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

I've searched the web repeatedly and can't find any solutions.

这是 Docker 文件.

Here's the Docker file.

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 错误.

And here is the Kestral error when I run the resultant image.

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

有人解决了吗?

推荐答案

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

Because this gets so much traffic, I'm adding the fully detailed code that you need to get this done.

# 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

这篇关于如何在 Linux 上的 Docker 中以非 root 用户身份运行 .NET Core 2 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆