Docker部署WebAPI后如何访问?附部署流程及启动日志
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:8080in 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 athttp://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.jsonfile for aUrlsconfiguration value. - Your
Program.cscode, where you might have a line likeWebHost.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

