以非root用户运行容器时,绑定443端口出现Kestrel权限拒绝错误原因
我的Dockerfile配置如下:
FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS final ENV ASPNETCORE_URLS=https://+:443 ENV ASPNETCORE_HTTPS_PORT=443 RUN adduser --disabled-password --home /app --gecos '' nonroot && chown -R nonroot /app USER nonroot
容器运行时出现以下错误:
Unhandled exception. System.Net.Sockets.SocketException (13): Permission denied
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions.CreateDefaultBoundListenSocket(EndPoint endpoint)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketConnectionListener.Bind()
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory.BindAsync(EndPoint endpoint, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.TransportManager.BindAsync(EndPoint endPoint, ConnectionDelegate connectionDelegate, EndpointConfig endpointConfig, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<>c__DisplayClass30_0`1.<g__OnBind|0>d.MoveNext()
我发现设置443以外的端口(如ENV ASPNETCORE_URLS=https://+:5080 ENV ASPNETCORE_HTTPS_PORT=5080)时,应用可以正常运行,请问出现该错误的原因是什么?
- Linux系统中,1-1023端口属于特权端口,这类端口的绑定权限仅开放给root用户,普通用户无法直接绑定
- 你的Dockerfile中切换到了nonroot普通用户,该用户没有权限绑定443这个特权端口,因此Kestrel在尝试绑定端口时触发了权限拒绝的SocketException
- 5080这类大于1023的端口是非特权端口,Linux系统允许普通用户直接绑定这类端口,所以应用能够正常启动运行
内容的提问来源于stack exchange,提问作者user584018

