You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台程序Docker部署无法绑定0.0.0.0端口求助

问题:Docker容器中C#控制台程序端口访问异常

在Docker容器中运行C#控制台程序时遇到以下端口问题:

  • 绑定0.0.0.0:1234会抛出错误:System.Net.HttpListenerException: 'The request is not supported.'
  • 绑定localhost:1234无报错,但外部浏览器无法访问服务

相关配置

代码示例

using System.Net;
using System.Text;

string html = "<html><body><h1>Hello World</h1></body></html>";

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://0.0.0.0:1234/");
//listener.Prefixes.Add("http://localhost:1234/");

listener.Start();

while (true)
{
    HttpListenerContext context = listener.GetContext();
    HttpListenerResponse response = context.Response;

    byte[] buffer = Encoding.UTF8.GetBytes(html);
    response.ContentLength64 = buffer.Length;

    Stream output = response.OutputStream;
    output.Write(buffer, 0, buffer.Length);

    output.Close();
}

Dockerfile

FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
EXPOSE 1234
USER app
WORKDIR /app

[...]

docker-compose.yml

services:
  demo:
    image: ${DOCKER_REGISTRY-}demo
    build:
      context: .
      dockerfile: demo/Dockerfile
    ports:
      - "1234:1234"

已尝试操作

  • 本地运行代码绑定localhost:1234正常
  • 容器内绑定localhost:1234时端口映射正常,但外部无法访问
  • 更换多个端口(80、8080、1234)均无效
  • 查询相关环境变量文档,仅找到ASP.NET相关内容

解决方案

核心修改:调整HttpListener监听前缀

将代码中的监听前缀从http://0.0.0.0:1234/修改为http://+:1234/,修改后的代码片段:

listener.Prefixes.Add("http://+:1234/");

原因说明

  • Linux环境下的HttpListener不支持直接使用0.0.0.0作为前缀的主机标识,使用+才能表示监听容器内所有可用的网络接口
  • 绑定localhost时,服务仅监听容器内部的回环接口,外部请求通过端口映射无法到达该接口,因此无法访问

其他注意事项

  • 由于1234是大于1024的端口,容器内的app用户无需额外权限即可监听,无需修改Dockerfile中的用户配置
  • 保持现有Dockerfile的EXPOSE 1234和docker-compose.yml的端口映射配置不变即可

完成修改后,重新构建并启动容器,外部浏览器访问http://localhost:1234即可正常访问服务。


内容的提问来源于stack exchange,提问作者Jan Rothkegel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:10:03