Start hereQuick start

Start here

Quick start

Write an App with a ConfigMap, a Deployment and a Service, render it, apply it, and give production its own size.

This page builds a small application: a Deployment, the ConfigMap it reads and the Service in front of it. It assumes the installation is done, with the default locations: manifest classes under src/K8S/ in the namespace App\K8S\. No YAML is written by hand.

1. Create an App

An App groups the manifests that deploy together under one name, the way a Helm chart groups templates. Scaffold one:

bin/console k8s:make:app shop
src/K8S/Shop/ShopApp.phnsrc/K8S/Shop/ShopApp.php
namespace App\K8S\Shop;

use Klass8s\App\AbstractApp;

class ShopApp extends AbstractApp
{
    static name(): string => 'shop';
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop;

use Klass8s\App\AbstractApp;

class ShopApp extends AbstractApp
{
    public static function name(): string
    {
        return 'shop';
    }
}

That is the file k8s:make:app writes: the Phaenon tab shows it in a Phaenon project, the PHP tab in a PHP project. It is the whole class, and the quick start keeps it as it is. From here on the classes are yours to write. bin/console k8s:make:manifest <short name> <kind> --app=shop would scaffold a starting point for each of the next three (Installation shows one); the steps show the finished classes. Every resource of this App is named shop-<short name> and labelled as part of shop. The App is found because it is a service in the container, like every class under src/; there is no list to register it in. k8s:make:app also creates the App's Manifest/, Container/ and Resources/ directories.

2. Add a ConfigMap

src/K8S/Shop/Manifest/ApiConfigMap.phnsrc/K8S/Shop/Manifest/ApiConfigMap.php
namespace App\K8S\Shop\Manifest;

use K8Schema\Collection\StringMap;
use Klass8s\Core\ConfigMap\AbstractConfigMap;

class ApiConfigMap extends AbstractConfigMap
{
    const string KEY_CACHE_HOST = 'CACHE_HOST';

    static shortName(): string => 'config';

    data(StringMap $data): void {
        $data->add(self::KEY_CACHE_HOST, 'valkey.cache.svc.cluster.local');
        $data->add('LOG_LEVEL', 'info');
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use K8Schema\Collection\StringMap;
use Klass8s\Core\ConfigMap\AbstractConfigMap;

class ApiConfigMap extends AbstractConfigMap
{
    public const string KEY_CACHE_HOST = 'CACHE_HOST';

    public static function shortName(): string
    {
        return 'config';
    }

    public function data(StringMap $data): void
    {
        $data->add(self::KEY_CACHE_HOST, 'valkey.cache.svc.cluster.local');
        $data->add('LOG_LEVEL', 'info');
    }
}

Each manifest class produces one Kubernetes resource and states its short name; the resource name is derived from it and the App's name: shop-config. The key name is a constant, so other classes refer to it by name rather than by retyping the string.

3. Add the Deployment

src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Lifecycle\Probes\ProbesConfigurator;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    const int PORT = 8080;

    static shortName(): string => 'api';

    image(): Image => Image::fromName('acme/shop-api')->setTag('1.0.0')->setRegistryUrl('registry.example.com');

    replicas(): int => 2;

    ports(PortsConfigurator $ports): void => $ports->add(self::PORT)->setName('http');

    env(EnvConfigurator $env): void => $env->addConfigMapClass(ApiConfigMap::class);

    resources(ContainerResourcesInterface $resources): void {
        $resources
            ->requestCPU(CPU::millicores(100))
            ->requestMemory(Memory::mebibytes(128))
            ->limitCPU(CPU::millicores(500))
            ->limitMemory(Memory::mebibytes(512));
    }

    probes(ProbesConfigurator $probes): void {
        $probes->readinessProbe()
            ->setInitialDelaySeconds(5)
            ->setPeriodSeconds(15)
            ->action()->httpGet(self::PORT)->setPath('/health');
    }

}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Lifecycle\Probes\ProbesConfigurator;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    public const int PORT = 8080;

    public static function shortName(): string
    {
        return 'api';
    }

    public function image(): Image
    {
        return Image::fromName('acme/shop-api')->setTag('1.0.0')->setRegistryUrl('registry.example.com');
    }

    public function replicas(): int
    {
        return 2;
    }

    public function ports(PortsConfigurator $ports): void
    {
        $ports->add(self::PORT)->setName('http');
    }

    public function env(EnvConfigurator $env): void
    {
        $env->addConfigMapClass(ApiConfigMap::class);
    }

    public function resources(ContainerResourcesInterface $resources): void
    {
        $resources
            ->requestCPU(CPU::millicores(100))
            ->requestMemory(Memory::mebibytes(128))
            ->limitCPU(CPU::millicores(500))
            ->limitMemory(Memory::mebibytes(512));
    }

    public function probes(ProbesConfigurator $probes): void
    {
        $probes->readinessProbe()
            ->setInitialDelaySeconds(5)
            ->setPeriodSeconds(15)
            ->action()->httpGet(self::PORT)->setPath('/health');
    }

}

AbstractContainerDeployment is the base class for a Deployment whose pod has one main container, which covers most services: the class is the Deployment and its container at once. Pods with several containers are in Containers.

Two details matter:

  • addConfigMapClass(ApiConfigMap::class) turns every key of the ConfigMap into an environment variable. It names the class, and Klass8s resolves the resource name, shop-config, when it renders. There is no string to keep in step.
  • CPU::millicores(100) and Memory::mebibytes(128) are value objects. A wrong unit or a quantity in a string fails the type check, not the API server.

4. Add the Service

src/K8S/Shop/Manifest/ApiService.phnsrc/K8S/Shop/Manifest/ApiService.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;

class ApiService extends AbstractService
{
    // the Deployment's short name, so the resource name is the same: shop-api
    static shortName(): string => ApiDeployment::shortName();

    ports(ServicePortsConfigurator $ports): void => $ports->add(80, ApiDeployment::PORT)->setName('http');
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;

class ApiService extends AbstractService
{
    // the Deployment's short name, so the resource name is the same: shop-api
    public static function shortName(): string
    {
        return ApiDeployment::shortName();
    }

    public function ports(ServicePortsConfigurator $ports): void
    {
        $ports->add(80, ApiDeployment::PORT)->setName('http');
    }
}

There is no selector. A Service whose short name is a workload's short name selects that workload's pods: Klass8s copies the Deployment's labels into the Service's selector (a default you can switch off). The target port is ApiDeployment::PORT, one constant on both sides of the connection.

5. Render

bin/console k8s:render:apps

The output is plain multi-document YAML, each document after a # File: comment that names the file k8s:dump:apps would write it to:

Renderedbin/console k8s:render:apps shop
# File: /shop/config.config-map.yaml
apiVersion: v1
kind: ConfigMap
data:
  CACHE_HOST: valkey.cache.svc.cluster.local
  LOG_LEVEL: info
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: config
  name: shop-config
---
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
  name: shop-api
spec:
  replicas: 2
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: api
  template:
    metadata:
      annotations:
        klass8s.dev/env-sources-checksum: f20fd65186b6e6b15ce9556c2700dd89
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: api
    spec:
      containers:
        -
          envFrom:
            - { configMapRef: { name: shop-config, optional: false } }
          image: 'registry.example.com/acme/shop-api:1.0.0'
          imagePullPolicy: IfNotPresent
          name: app
          ports:
            - { containerPort: 8080, name: http }
          readinessProbe:
            httpGet: { path: /health, port: 8080 }
            initialDelaySeconds: 5
            periodSeconds: 15
          resources:
            limits: { cpu: 500m, memory: 512Mi }
            requests: { cpu: 100m, memory: 128Mi }
---
# File: /shop/api.service.yaml
apiVersion: v1
kind: Service
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
  name: shop-api
spec:
  ports:
    -
      name: http
      port: 80
      targetPort: 8080
  selector:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
  trafficDistribution: PreferClose

What you did not write: the labels and the selector that match them, the names resolved from class references, and the klass8s.dev/env-sources-checksum annotation on the pod template, a fingerprint of the ConfigMap and the Secrets the pod reads through its environment. Change LOG_LEVEL and render again, and the checksum changes, so applying the new output restarts this Deployment's pods, and only the pods of workloads that read that ConfigMap. Its sibling, volume-sources-checksum, fingerprints the ConfigMaps and Secrets mounted as volumes; with none, it is the checksum of nothing.

Defaults fill the rest: revisionHistoryLimit: 1, imagePullPolicy: IfNotPresent, a container named app, and the PreferClose traffic distribution on the Service.

6. Apply

# what would change
bin/console k8s:render:apps | kubectl diff -f -

# apply it
bin/console k8s:render:apps | kubectl apply -f -

# or write one file per resource: var/k8s-manifests/dev/apps/shop/api.deployment.yaml, …
bin/console k8s:dump:apps

render prints to standard output and dump writes files. Both are deterministic: the same code, configuration and APP_ENV give byte-identical output, which is what makes kubectl diff and a review of the output worth reading.

7. Give production its own size

Production needs more replicas and more room. Add two methods to ApiDeployment:

src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
replicasProd(): int => 6;

resourcesProd(ContainerResourcesInterface $resources): void {
    $resources
        ->requestCPU(CPU::millicores(500))
        ->requestMemory(Memory::mebibytes(512))
        ->limitCPU(CPU::cores(2))
        ->limitMemory(Memory::gibibytes(1));
}
public function replicasProd(): int
{
    return 6;
}

public function resourcesProd(ContainerResourcesInterface $resources): void
{
    $resources
        ->requestCPU(CPU::millicores(500))
        ->requestMemory(Memory::mebibytes(512))
        ->limitCPU(CPU::cores(2))
        ->limitMemory(Memory::gibibytes(1));
}
APP_ENV=prod bin/console k8s:render:apps | kubectl diff -f -

With APP_ENV=prod, Klass8s calls replicasProd() where it would call replicas(), and calls resourcesProd() after resources() on the same configurator, so production starts from the base values and replaces what it sets. The suffix is the environment's name; a method whose signature differs from the one it stands for fails the render. Everything that differs between environments for this Deployment is in this class:

RenderedAPP_ENV=prod bin/console k8s:render:apps shop
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
  name: shop-api
spec:
  replicas: 6
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: api
  template:
    metadata:
      annotations:
        klass8s.dev/env-sources-checksum: f20fd65186b6e6b15ce9556c2700dd89
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: api
    spec:
      containers:
        -
          envFrom:
            - { configMapRef: { name: shop-config, optional: false } }
          image: 'registry.example.com/acme/shop-api:1.0.0'
          imagePullPolicy: IfNotPresent
          name: app
          ports:
            - { containerPort: 8080, name: http }
          readinessProbe:
            httpGet: { path: /health, port: 8080 }
            initialDelaySeconds: 5
            periodSeconds: 15
          resources:
            limits: { cpu: '2', memory: 1Gi }
            requests: { cpu: 500m, memory: 512Mi }

Environments covers the other tools: methods added in some environments only, manifests that exist in some environments only, and configuration files per environment.

What you built

You wroteKlass8s derived
four small classesnames, labels, the selector, the Service's wiring
class references and constantsresource names, environment variables, ports
replicasProd() and resourcesProd()the production variant
nothingrestarts when the configuration changes

Next