Kubernetes inside docker

Nov 16, 2021 | - views

Docker-compose

version: "3"

services:
  server:
    image: "rancher/k3s:latest"
    command: server
    tmpfs:
      - /run
      - /var/run
    ulimits:
      nproc: 65535
      nofile:
        soft: 65535
        hard: 65535
    privileged: true
    restart: always
    environment:
      - K3S_TOKEN=10271321911015
      - K3S_KUBECONFIG_OUTPUT=/output/kubeconfig.yaml
      - K3S_KUBECONFIG_MODE=666
    volumes:
      - k3s-server:/var/lib/rancher/k3s
      - .:/output
    ports:
      - 6443:6443  # Kubernetes API Server
      - 80:80      # Ingress controller port 80
      - 443:443    # Ingress controller port 443

  agent:
    image: "rancher/k3s:latest"
    tmpfs:
      - /run
      - /var/run
    ulimits:
      nproc: 65535
      nofile:
        soft: 65535
        hard: 65535
    privileged: true
    restart: always
    environment:
      - K3S_URL=https://server:6443
      - K3S_TOKEN=10271321911015

volumes:
  k3s-server: { }

Spring application configuration

<dependency>
    <groupId>io.kubernetes</groupId>
    <artifactId>client-java</artifactId>
    <version>${kubernetes-client.version}</version>
</dependency>
@Configuration
public class ApiConfig {
  @Bean
  public ApiClient apiClient() throws IOException {
    try (var reader = Files.newBufferedReader(Path.of("./kubeconfig.yaml"))) {
      return ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(reader)).build();
    }
  }

  @Bean
  public CoreV1Api coreV1Api(ApiClient apiClient) {
    return new CoreV1Api(apiClient);
  }
}
@Service
@RequiredArgsConstructor
class ExampleService {
  private final CoreV1Api coreApi;

  @Scheduled(fixedRate = 5000L)
  public void invoke() throws ApiException {
    coreApi.listNamespacedPod(
        "your-namespace",
        null,
        null,
        null,
        null,
        "app=deployment-name",
        null,
        null,
        null,
        null
    ).getItems();
  }
}