> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-docs-es/kilo-center/kilo-mioty-service-center/getting-started/installation-kubernetes-helm.md).

# Instalación: Kubernetes (Helm)

Despliega KiloCenter en Kubernetes con Helm — chart, requisitos previos (k8s 1.25+, PostgreSQL 14+, Redis 7+) e ingress.

### Objetivo

Despliega KiloCenter en un clúster de Kubernetes usando el chart de Helm incluido en este repositorio.

### Requisitos previos

| Requisito             | Versión mínima |
| --------------------- | -------------- |
| Clúster de Kubernetes | 1.25+          |
| Helm                  | 3.x            |
| PostgreSQL externo    | 14+            |
| Redis externo         | 7+             |

PostgreSQL y Redis **no** se despliegan con este chart. Aprovisiónalos por separado (servicios gestionados, operadores o independientes) y proporciona los detalles de conexión en tu sobreescritura de valores.

### Arquitectura

```
                  Internet
                     |
               [ Ingress ] (opcional)
                /         \
         kc-web:80    kc-gateway:9090
                          |
                    kc-core:50051 ---- kc-identity:50052
                    /      |      \
             bssci:5000  scaci:5001  mosquitto:1883
                                         |
                                    [Clientes MQTT]
```

El chart despliega cinco servicios y un broker MQTT:

| Componente    | Puerto(s)                                              | Descripción                                        |
| ------------- | ------------------------------------------------------ | -------------------------------------------------- |
| `kc-core`     | 50051 (gRPC), 5000 (BSSCI), 5001 (SCACI), 8086 (salud) | Motor del centro de servicios                      |
| `kc-gateway`  | 9090 (gRPC-web), 8087 (salud)                          | Entrada de API externa                             |
| `kc-identity` | 50052 (gRPC), 8088 (salud)                             | Identidad, usuarios, organizaciones                |
| `kc-web`      | 80                                                     | Interfaz web de administración (nginx)             |
| `mosquitto`   | 1883, 9001 (WebSocket)                                 | Broker MQTT                                        |
| `certgen`     | —                                                      | Hook de preinstalación que genera certificados TLS |

### Paso 1: Crea una sobreescritura de valores

Como mínimo, sobrescribe la configuración de la base de datos, Redis y los secretos:

```yaml
# my-values.yaml
postgresql:
  host: my-postgres.default.svc.cluster.local
  password: "a-strong-password"
  sslMode: "require"

redis:
  host: my-redis.default.svc.cluster.local

secrets:
  authHmacSecret: "replace-with-a-random-string-at-least-32-bytes"
  mqttAdminPassword: "strong-mqtt-admin-pw"
  mqttClientPassword: "strong-mqtt-client-pw"

certgen:
  serverName: "kilocenter.example.com"
```

> **Importante:** El `authHmacSecret` se usa para firmar y verificar tokens JWT entre KC-Gateway y KC-Identity. Debe tener al menos 32 caracteres.

### Paso 2: Instalar

```bash
helm install kilocenter ./helm/kilocenter -f my-values.yaml
```

En la primera instalación, un Job hook de preinstalación ejecuta el binario `certgen` para generar una CA autofirmada y un certificado de servidor en un PVC compartido. Las actualizaciones posteriores omiten la generación si los certificados ya existen.

### Paso 3: Validar

```bash
# Comprueba que todos los pods estén en ejecución
kubectl get pods -l app.kubernetes.io/instance=kilocenter

# Comprueba la salud del servicio
kubectl exec deploy/kilocenter-kc-core -- wget -qO- http://localhost:8086/health/ping
kubectl exec deploy/kilocenter-kc-identity -- wget -qO- http://localhost:8088/health
kubectl exec deploy/kilocenter-kc-gateway -- wget -qO- http://localhost:8087/health
```

### Paso 4: Acceder a la interfaz

Sin ingress, usa el reenvío de puertos:

```bash
kubectl port-forward svc/kilocenter-kc-web 8080:80
```

Luego abre <http://localhost:8080/> en tu navegador.

### Cuenta de administrador predeterminada

En el primer arranque, se crea un usuario administrador predeterminado mediante una migración de base de datos:

|                        |                               |
| ---------------------- | ----------------------------- |
| **Correo electrónico** | `admin [at] kilocenter.local` |
| **Contraseña**         | `admin123!`                   |

> Reemplaza `[at]` por `@` al iniciar sesión.

> **Advertencia:** Cambia la contraseña o elimina esta cuenta antes de cualquier despliegue orientado al público. Las credenciales están publicadas en este repositorio.

### Ingress

Habilita el Ingress estándar de Kubernetes en tu sobreescritura de valores:

```yaml
ingress:
  enabled: true
  className: nginx
  hosts:
    - host: kilocenter.example.com
      paths:
        - path: /
          pathType: Prefix
          service: kc-web
          port: 80
        - path: /kilocenter.api
          pathType: Prefix
          service: kc-gateway
          port: 9090
  tls:
    - secretName: kilocenter-tls
      hosts:
        - kilocenter.example.com
```

Al usar ingress, añade tu dominio a los orígenes permitidos de CORS:

```yaml
kcGateway:
  config:
    corsOrigins:
      - "https://kilocenter.example.com"
```

### Acceso al protocolo BSSCI/SCACI

Las estaciones base se conectan directamente a KC-Core mediante TCP+TLS en los puertos 5000 (BSSCI) y 5001 (SCACI). Estas son conexiones TCP sin procesar, no HTTP. Para exponerlas externamente, crea un servicio LoadBalancer:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: kilocenter-bssci
spec:
  type: LoadBalancer
  selector:
    app.kubernetes.io/name: kc-core
    app.kubernetes.io/instance: kilocenter
  ports:
    - name: bssci
      port: 5000
      targetPort: 5000
    - name: scaci
      port: 5001
      targetPort: 5001
```

### Certificados TLS

El `certgen` El hook genera una CA autofirmada y un certificado de servidor en la primera instalación. Para producción, reemplázalos por certificados firmados por una CA de confianza montando tu propio secreto o PVC en `/app/certificates` en el pod kc-core.

### Referencia de configuración

Para la lista completa de parámetros configurables, consulta el README del chart de Helm.

### Actualización

```bash
helm upgrade kilocenter ./helm/kilocenter -f my-values.yaml
```

Establece una etiqueta de imagen específica para fijar una versión:

```yaml
global:
  imageTag: "1.0.0"
```

### Solución de problemas

| Síntoma                                   | Causa probable                             | Solución                                                                               |
| ----------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------- |
| Pods en `ImagePullBackOff`                | Falta el secreto de extracción de imágenes | Añade `global.imagePullSecrets` con las credenciales de tu registro                    |
| 503 en la sonda de preparación de KC-Core | Dependencia no lista                       | Comprueba que KC-Identity y PostgreSQL estén en ejecución                              |
| `invalid_token` después de iniciar sesión | Desajuste del secreto HMAC                 | Asegúrate de `secrets.authHmacSecret` esté configurado (igual para gateway e identity) |
| Conexión BSSCI rechazada                  | Sin servicio externo                       | Crea un servicio LoadBalancer para los puertos 5000/5001                               |
| Errores de gRPC-web en el navegador       | CORS o ingress mal configurado             | Comprueba `kcGateway.config.corsOrigins` y las rutas del ingress                       |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.kiloiot.io/kilo-docs-es/kilo-center/kilo-mioty-service-center/getting-started/installation-kubernetes-helm.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
