K3s
Warning
This container runs privileged, as it spawns its own containers. For this reason, this container will not work in certain rootless Docker, Docker-in-Docker, or other environments that disallow privileged containers.
Install
| npm install @testcontainers/k3s --save-dev
|
Examples
These examples use the following libraries:
Choose an image from the container registry and substitute IMAGE
.
List nodes
| await using container = await new K3sContainer(IMAGE).start();
const kubeConfig = new k8s.KubeConfig();
kubeConfig.loadFromString(container.getKubeConfig());
const client = kubeConfig.makeApiClient(k8s.CoreV1Api);
const nodeList = await client.listNode();
expect(nodeList.items).toHaveLength(1);
|
Start a pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 | await using container = await new K3sContainer(IMAGE).start();
const kubeConfig = new k8s.KubeConfig();
kubeConfig.loadFromString(container.getKubeConfig());
const pod = {
metadata: {
name: "helloworld",
},
spec: {
containers: [
{
name: "helloworld",
image: "testcontainers/helloworld:1.1.0",
ports: [
{
containerPort: 8080,
},
],
readinessProbe: {
tcpSocket: {
port: 8080,
},
},
},
],
},
};
const client = kubeConfig.makeApiClient(k8s.CoreV1Api);
await client.createNamespacedPod({ namespace: "default", body: pod });
await vi.waitFor(async () => {
const { status } = await client.readNamespacedPodStatus({ namespace: "default", name: "helloworld" });
return (
status?.phase === "Running" &&
status?.conditions?.some((cond) => cond.type === "Ready" && cond.status === "True")
);
}, 60_000);
|
Aliased kubeconfig
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | await using network = await new Network().start();
await using container = await new K3sContainer(IMAGE).withNetwork(network).withNetworkAliases("k3s").start();
const kubeConfig = container.getAliasedKubeConfig("k3s");
await using kubectlContainer = await new GenericContainer(KUBECTL_IMAGE)
.withNetwork(network)
.withCopyContentToContainer([{ content: kubeConfig, target: "/home/kubectl/.kube/config" }])
.withCommand(["get", "namespaces"])
.withWaitStrategy(Wait.forOneShotStartup())
.start();
const chunks = await (await kubectlContainer.logs()).toArray();
expect(chunks).toEqual(expect.arrayContaining([expect.stringContaining("kube-system")]));
|