使用Kubernetes+Docker部署.NET Core应用无法脱离默认80端口
Hey there! Let's figure out why your .NET Core app is stuck using port 80 after deployment, even though you configured Kestrel to listen on 8080 in Program.cs. Here's a step-by-step breakdown of possible issues and fixes:
1. Check Your Dockerfile Configuration
First, let's make sure your Dockerfile isn't overriding your Kestrel settings:
- Verify the
EXPOSEdirective: Make sure it's set to8080instead of80:EXPOSE 8080 - Check for
ASPNETCORE_URLSenvironment variable: This environment variable takes precedence over code-based Kestrel config. If your Dockerfile has something like this, it'll force the app to use port 80:
Replace it with:ENV ASPNETCORE_URLS=http://+:80ENV ASPNETCORE_URLS=http://+:8080 - Confirm the startup command: Ensure your
ENTRYPOINT/CMDis correctly launching the app without hardcoding port 80. A correct entrypoint looks like:ENTRYPOINT ["dotnet", "YourAppName.dll"]
2. Validate Kubernetes Deployment & Service
Most port issues in Kubernetes come from misconfigured port mappings:
Deployment Container Ports
Double-check that your Deployment's container is set to expose port 8080:
apiVersion: apps/v1 kind: Deployment metadata: name: your-app-deployment spec: replicas: 1 selector: matchLabels: app: your-app template: metadata: labels: app: your-app spec: containers: - name: your-app-container image: your-docker-image:tag ports: - containerPort: 8080 # This must match your Kestrel port protocol: TCP # Optional: Set ASPNETCORE_URLS here if not in Dockerfile env: - name: ASPNETCORE_URLS value: "http://+:8080"
Service Port Mapping
Your Kubernetes Service needs to route traffic to the correct container port (targetPort: 8080), even if you expose port 80 externally:
apiVersion: v1 kind: Service metadata: name: your-app-service spec: selector: app: your-app ports: - port: 80 # External port (can be any, e.g., 8080 too) targetPort: 8080 # Must match containerPort and Kestrel port protocol: TCP type: ClusterIP # Or NodePort/LoadBalancer depending on your needs
3. Verify Kestrel is Actually Listening on 8080
Let's confirm your app is behaving as expected inside the pod:
- Check pod logs: Run
kubectl logs <your-pod-name>and look for lines like:Now listening on: http://127.0.0.1:8080
If you see port 80 instead, your Kestrel config is being overridden (go back to Dockerfile/Deployment env vars). - Test inside the pod: Exec into the pod and test the port directly:
If this works, the app is fine—issue is in Kubernetes routing. If not, your app isn't listening on 8080 (check code/Dockerfile).kubectl exec -it <your-pod-name> -- /bin/bash # Then run: curl localhost:8080/api/test
4. Check for Overlapping Configurations
- Ensure
appsettings.jsonorappsettings.Production.jsondoesn't have a Kestrel config that overrides your code:
If present, update the port to 8080."Kestrel": { "Endpoints": { "Http": { "Url": "http://+:80" } } }
内容的提问来源于stack exchange,提问作者JMadelaine

