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

Docker部署WebAPI后如何访问?附部署流程及启动日志

How to Access Your ASP.NET Core WebAPI Running in a Docker Container

Original Question

I have the following Dockerfile:

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /build
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o output
FROM microsoft/aspnetcore:2.0
WORKDIR /app
COPY --from=build /build/output .
ENTRYPOINT ["dotnet","TestDockerApi.dll"]

I built the image with: docker build -t testdocker/api .
Then ran the container: docker run testdocker/api
The console shows: Hosting environment: Production Content root path...
How do I access this WebAPI after deployment?


The core issue here is missing port mapping between your host machine and the Docker container. Containers run in isolated network environments by default—their internal ports aren't directly accessible from the host unless you explicitly link them. Here's how to fix this:

Step 1: Run the container with port mapping

Use the -p flag in your docker run command to bind a port on your host to the port your WebAPI listens on inside the container.

For ASP.NET Core 2.0, the default listening port is usually 5000 (unless you configured Kestrel to use a different port like 80). Replace your run command with one of these:

# Map host port 8080 to container port 5000 (default for ASP.NET Core 2.0)
docker run -p 8080:5000 testdocker/api

Or if your API is configured to listen on port 80 inside the container:

docker run -p 8080:80 testdocker/api

Step 2: Access the WebAPI

Once the container is running with port mapping:

  • If you're running Docker locally, visit http://localhost:8080 in your browser or use tools like Postman to send requests.
  • Append your API's route paths to this base URL. For example, if you have a default ValuesController, you'd access it at http://localhost:8080/api/values.

Step 3: Verify port mapping (optional)

To confirm the port is correctly linked, run docker ps in your terminal. Look for a line like 0.0.0.0:8080->5000/tcp under the PORTS column—this confirms your host's port 8080 is connected to the container's port 5000.

Bonus: Check your API's listening port

If you're unsure which port your API uses inside the container, check:

  • Your appsettings.json file for a Urls configuration value.
  • Your Program.cs code, where you might have a line like WebHost.CreateDefaultBuilder(args).UseUrls("http://*:5000").

Make sure the container port in your docker run command matches the port your API is configured to listen on.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:41:28