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

使用docker-compose启动.NET Core项目集群时如何访问各API的Swagger

解决Docker Compose启动后无法访问Web API Swagger的问题

问题原因

你当前的docker-compose.yml中,仅为mongo-express配置了端口映射,而mygateway.api和identity.api没有将容器内部的服务端口映射到主机端口。Docker容器默认是网络隔离的,主机无法直接访问未做端口映射的容器服务。

解决方案

给每个Web API服务添加ports配置项,将容器内的服务端口映射到主机的不同端口(避免端口冲突),同时确保API项目的Swagger在当前运行环境下已启用。

修改后的docker-compose.yml示例

version: '3.4'

services:
  myserver.frontend:
    image: ${DOCKER_REGISTRY-}myserverfrontend
    build:
      context: .
      dockerfile: Server/MyServer.Frontend/Dockerfile
    # 保持前端端口映射(若原有配置已包含可忽略,此处示例映射80端口)
    ports:
      - "80:80"

  mygateway.api:
    image: ${DOCKER_REGISTRY-}mygatewayapi
    build:
      context: .
      dockerfile: Services/MyGateway.API/Dockerfile
    # 添加端口映射,主机5000端口对应容器内80端口(根据API实际监听端口调整)
    ports:
      - "5000:80"
    # 指定运行环境为开发环境,确保Swagger启用
    environment:
      - ASPNETCORE_ENVIRONMENT=Development

  identity.api:
    image: ${DOCKER_REGISTRY-}identityapi
    build:
      context: .
      dockerfile: Services/Identity.API/Dockerfile
    # 添加端口映射,主机5001端口对应容器内80端口
    ports:
      - "5001:80"
    environment:
      - ASPNETCORE_ENVIRONMENT=Development

  # Install the mongodb for offline data storage
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: root
      ME_CONFIG_MONGODB_URL: mongodb://root:root@mongo:27017/

访问方式

  • Blazor前端:访问http://localhost(若映射的是80端口)
  • MyGateway.API Swagger:访问http://localhost:5000/swagger
  • Identity.API Swagger:访问http://localhost:5001/swagger

注意事项

  1. 确认API项目的Program.cs中已启用Swagger,且仅在开发环境启用的逻辑正确(比如通过if (app.Environment.IsDevelopment())判断)。
  2. 主机端口可自行调整,只要不与其他本地服务冲突即可。
  3. 若你的API容器内监听的不是80端口(比如Dockerfile中用了EXPOSE 8080),则端口映射要改为"主机端口:容器端口"(如5000:8080)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:42:56