AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1176094
Accepted
pf12345678910
pf12345678910
Asked: 2025-03-20 21:38:50 +0800 CST2025-03-20 21:38:50 +0800 CST 2025-03-20 21:38:50 +0800 CST

K8 - Pod escuta na porta 8080, mas o Node redefine a conexão na porta externa

  • 772

Implantei uma API C# em um cluster Kubernetes

Pelo que entendi, deveríamos ter: GET http request -> Node(30000) -> Pod(80) -> C# API(8080)

Minha imagem docker expõe a porta 8080

FROM our-registry/dotnet/sdk:8.0 AS build
WORKDIR /app

# Copy the project file and restore any dependencies (use .csproj for the project name)
COPY MyApi/MyApi/*.csproj ./
RUN dotnet restore

# Copy the rest of the application code
COPY MyApi/MyApi/. ./

# Publish the application
ARG BUILD_CONFIG=Release
RUN echo "Building with configuration: ${BUILD_CONFIG}"
RUN dotnet publish -c ${BUILD_CONFIG} -o out

# Build the runtime image
FROM our-registry/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/out ./

# Expose the port your application will run on
EXPOSE 8080

# Start the application
ENTRYPOINT ["dotnet", "MyApi.dll"]

Meu K8 api-service.yaml está definido assim

apiVersion: v1
kind: Service
metadata:
  name: my-api-service
  namespace: somenamespace
spec:
  selector:
    app: my-api
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30000
  type: NodePort 

Minhas configurações de inicialização da API C# configuram a porta 8080 e funcionam bem localmente em depuração/lançamento nessa porta

{
  "profiles": {
    "http": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
        "environmentVariables": {
            ...
        },
      "dotnetRunMessages": true,
      "applicationUrl": "http://localhost:8080"
    },
    "https": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
        "environmentVariables": {
            ...
        },
      "dotnetRunMessages": true,
      "applicationUrl": "https://localhost:7084;http://localhost:8080"
    },
    ...

No cluster, o serviço é executado

kubectl get svc -n somenamespace

NAME                  TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
my-api-service        NodePort   10.*.*.*   <none>        80:30000/TCP   3h56m

Naquele casulo

kubectl get pods -n somenamespace -o wide
NAME                           READY   STATUS    RESTARTS   AGE    IP             NODE                                          NOMINATED NODE   READINESS GATES
my-apipod-*********-*****   1/1     Running   0          138m   10.*.*.*   somenode   <none>           <none>

Eu verifiquei localmente dentro do pod

kubectl exec -it my-apipod-*********-***** -n somenamespace -- bash
...
root@my-apipod-*********-*****:/app# netstat -tulnp | grep LISTEN
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      1/dotnet    

Obtendo o nó

kubectl get nodes -o wide
NAME                                          STATUS   ROLES                       AGE    VERSION           INTERNAL-IP      EXTERNAL-IP      OS-IMAGE                         KERNEL-VERSION      CONTAINER-RUNTIME
somenode   Ready    worker                      108d   v1.28.11+rke2r1   192.168.1.23   192.168.1.23  Ubuntu 20.04.6 LTS               5.4.0-200-generic   containerd://1.7.17-k3s1

Tento conectar no ip desse nó com o nodePort 30000

curl -X GET http://192.168.1.23:30000/swagger/index.html -v
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 192.168.1.23:30000...
* Connected to 192.168.1.23 (192.168.1.23) port 30000 (#0)
> GET /swagger/index.html HTTP/1.1
> Host: 192.168.1.23:30000
> User-Agent: curl/7.81.0
> Accept: */*
> 
* Recv failure: Connection reset by peer
* Closing connection 0
curl: (56) Recv failure: Connection reset by peer

Não tenho certeza do que mais verificar. Executei meu código de API (.NET) localmente e o swagger está funcionando e acessível.

Obrigado pela ajuda

[editar]

Conforme faço solicitações como essas no navegador:

http://192.168.1.23:30000
http://192.168.1.23:30000/swagger/index.html

Nada aparece no log

kubectl logs -f -n mynamespace my-apipod-*********-*****
warn: Microsoft.AspNetCore.Hosting.Diagnostics[15]
      Overriding HTTP_PORTS '8080' and HTTPS_PORTS ''. Binding to values defined by URLS instead 'http://0.0.0.0:8080'.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://0.0.0.0:8080
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /app

Isso aparece se eu tentar https

warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
      Failed to determine the https port for redirect.

Então a API parece funcionar bem

kubernetes
  • 2 2 respostas
  • 123 Views

2 respostas

  • Voted
  1. Gebz
    2025-03-20T22:44:04+08:002025-03-20T22:44:04+08:00

    Primeiro passo da solução de problemas, faça um tcpdump no nó:

    # tcpdump -i any tcp port 30000
    

    Você também pode verificar os logs do aplicativo:

    $ kubectl logs -f -n <your_ns> <pod>
    

    A redefinição da conexão é uma indicação de que a conexão está chegando ao seu ponto de extremidade da API, mas um erro está causando a redefinição da conexão.

    • 0
  2. Best Answer
    pf12345678910
    2025-03-27T15:05:59+08:002025-03-27T15:05:59+08:00

    A resposta foi criar uma configuração de entrada

    apiVersion: traefik.io/v1alpha1
    kind: IngressRoute
    metadata:
      name: my-api
      namespace: mynamespace
    spec:
      entryPoints:
        - websecure
      routes:
        - kind: Rule
          match : >-
            (Host(`myapi.********`)) 
          services:
            - name: my-api-service
              port: 80
      tls:
        secretName: somecertificate
    
    • 0

relate perguntas

  • Containerd falhou ao iniciar após Nvidia Config

  • Como posso modificar o configmap CoreDNS antes de inicializar o cluster usando o kubeadm?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve