Skip to content

K3s Module

Note

This module is INCUBATING. While it is ready for use and operational in the current version of Testcontainers, it is possible that it may receive breaking changes in the future. See our contributing guidelines for more information on our incubating modules policy.

Testcontainers module for Rancher's K3s lightweight Kubernetes. This module is intended to be used for testing components that interact with Kubernetes APIs - for example, operators.

Usage example

Start a K3s server as follows:

K3sContainer k3s = new K3sContainer(DockerImageName.parse("rancher/k3s:v1.21.3-k3s1"))
    .withLogConsumer(new Slf4jLogConsumer(log))

Connecting to the server

K3sContainer exposes a working Kubernetes client configuration, as a YAML String, via the getKubeConfigYaml() method.

This may be used with Kubernetes clients - e.g. for the official Java client and the Fabric8 Kubernetes client:

String kubeConfigYaml = k3s.getKubeConfigYaml();

ApiClient client = Config.fromConfig(new StringReader(kubeConfigYaml));
CoreV1Api api = new CoreV1Api(client);

// interact with the running K3s server, e.g.:
V1NodeList nodes = api.listNode(null, null, null, null, null, null, null, null, null, null);
// obtain a kubeconfig file which allows us to connect to k3s
String kubeConfigYaml = k3s.getKubeConfigYaml();

// requires io.fabric8:kubernetes-client:5.11.0 or higher
Config config = Config.fromKubeconfig(kubeConfigYaml);

DefaultKubernetesClient client = new DefaultKubernetesClient(config);

// interact with the running K3s server, e.g.:
List<Node> nodes = client.nodes().list().getItems();

Known limitations

Warning

  • K3sContainer runs as a privileged container and needs to be able to spawn its own containers. For these reasons, K3sContainer will not work in certain rootless Docker, Docker-in-Docker, or other environments where privileged containers are disallowed.

  • k3s containers may be unable to run on host machines where /var/lib/docker is on a BTRFS filesystem. See k3s-io/k3s#4863 for an example.

  • You may experience PKIX exceptions when trying to use a configured Fabric8 client. This is down to newer distributions of k3s issuing elliptic curve keys. This can be fixed by adding BouncyCastle PKI library to your classpath.

Adding this module to your project dependencies

Add the following dependency to your pom.xml/build.gradle file:

testImplementation "org.testcontainers:k3s:1.19.0"
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>k3s</artifactId>
    <version>1.19.0</version>
    <scope>test</scope>
</dependency>