Manage Kubernetes Clusters with PHP and Laravel

Packages

February 11th, 2021

Laravel PHP K8s is a package that provides access to features offered by the excellent renoki-co/php-k8s package in Laravel. The underlying PHP K8s package is a PHP handler for the Kubernetes Cluster API. With it, you can automate the management of creating, deleting, updating, etc. individual Kubernetes resources directly from PHP.

Here is an example of how PHP K8s provides an object-oriented way to generate Kubernetes resources and configuration dynamically:

use RenokiCo\PhpK8s\KubernetesCluster;

// Create a new instance of KubernetesCluster
$cluster = new KubernetesCluster('http://127.0.0.1:8080');

// Create a new NGINX service.
$svc = $cluster->service()
    ->setName('nginx')
    ->setNamespace('frontend')
    ->setSelectors(['app' => 'frontend'])
    ->setPorts([
        [
            'protocol' => 'TCP',
            'port' => 80,
            'targetPort' => 80
        ],
    ])
    ->create();

Which would equal the following YAML configuration:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: frontend
spec:
  selector:
    app: frontend
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

The Laravel PHP package helps further with the above by handling connection configuration and allowing you to access the Kubernetes cluster. Here are some examples from the readme to get a taste of what you can do with this Laravel package:

use RenokiCo\LaravelK8s\LaravelK8sFacade;

foreach (LaravelK8sFacade::getAllConfigMaps() as $cm) {
    // $cm->getName();
}

There are multiple ways to connect to the cluster instance, which means you can configure them and specifiy the connection type to use from the k8s.php config:

// Specify the cluster connection type and get the cluster
$cluster = LaravelK8sFacade::connection('http')->getCluster();

// Get the cluster using the default connection type
$cluster = LaravelK8sFacade::getCluster();

You can learn more about this package, get full installation instructions, and view the source code on GitHub. I'd also recommend reading through the renoki-co/php-k8s documentation to learn how to manage Kubernetes with this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.