K3s¶
Since v0.21.0
Introduction¶
The Testcontainers module for K3s.
Adding this module to your project dependencies¶
Please run the following command to add the K3s module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/k3s
Usage example¶
package k3s_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/k3s"
"github.com/testcontainers/testcontainers-go/wait"
)
func Test_LoadImages(t *testing.T) {
// Give up to three minutes to run this test
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Minute))
defer cancel()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
require.NoError(t, err)
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
require.NoError(t, err)
k8s, err := kubernetes.NewForConfig(restcfg)
require.NoError(t, err)
provider, err := testcontainers.ProviderDocker.GetProvider()
require.NoError(t, err)
// ensure nginx image is available locally
err = provider.PullImage(ctx, "nginx")
require.NoError(t, err)
t.Run("Test load image not available", func(t *testing.T) {
err := k3sContainer.LoadImages(ctx, "fake.registry/fake:non-existing")
require.Error(t, err)
})
t.Run("Test load image in cluster", func(t *testing.T) {
err := k3sContainer.LoadImages(ctx, "nginx")
require.NoError(t, err)
pod := &corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx",
ImagePullPolicy: corev1.PullNever, // use image only if already present
},
},
},
}
_, err = k8s.CoreV1().Pods("default").Create(ctx, pod, metav1.CreateOptions{})
require.NoError(t, err)
err = kwait.PollUntilContextCancel(ctx, time.Second, true, func(ctx context.Context) (bool, error) {
state, err := getTestPodState(ctx, k8s)
if err != nil {
return false, err
}
if state.Terminated != nil {
return false, fmt.Errorf("pod terminated: %v", state.Terminated)
}
return state.Running != nil, nil
})
require.NoError(t, err)
state, err := getTestPodState(ctx, k8s)
require.NoError(t, err)
require.NotNil(t, state.Running)
})
}
func getTestPodState(ctx context.Context, k8s *kubernetes.Clientset) (corev1.ContainerState, error) {
var pod *corev1.Pod
var err error
pod, err = k8s.CoreV1().Pods("default").Get(ctx, "test-pod", metav1.GetOptions{})
if err != nil || len(pod.Status.ContainerStatuses) == 0 {
return corev1.ContainerState{}, err
}
return pod.Status.ContainerStatuses[0].State, nil
}
func Test_APIServerReady(t *testing.T) {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
require.NoError(t, err)
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
require.NoError(t, err)
k8s, err := kubernetes.NewForConfig(restcfg)
require.NoError(t, err)
pod := &corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx",
},
},
},
}
_, err = k8s.CoreV1().Pods("default").Create(context.Background(), pod, metav1.CreateOptions{})
require.NoError(t, err)
}
func Test_WithManifestOption(t *testing.T) {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx,
"rancher/k3s:v1.27.1-k3s1",
k3s.WithManifest("nginx-manifest.yaml"),
testcontainers.WithAdditionalWaitStrategy(wait.ForExec([]string{"kubectl", "wait", "pod", "nginx", "--for=condition=Ready"})),
)
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
}
Module Reference¶
Run function¶
- Since v0.32.0
Info
The RunContainer(ctx, opts...)
function is deprecated and will be removed in the next major release of Testcontainers for Go.
The K3s module exposes one entrypoint function to create the K3s container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*K3sContainer, error)
context.Context
, the Go context.string
, the Docker image to use.testcontainers.ContainerCustomizer
, a variadic argument for passing options.
Container Ports¶
These are the ports used by the K3s container:
defaultKubeSecurePort = "6443/tcp"
defaultRancherWebhookPort = "8443/tcp"
Image¶
Use the second argument in the Run
function to set a valid Docker image.
In example: Run(context.Background(), "rancher/k3s:v1.27.1-k3s1")
.
Container Options¶
When starting the K3s container, you can pass options in a variadic way to configure it.
WithManifest¶
- Since v0.29.0
The WithManifest
option loads a manifest obtained from a local file into the cluster. K3s applies it automatically during the startup process
func WithManifest(manifestPath string) testcontainers.CustomizeRequestOption
Example:
WithManifest("nginx-manifest.yaml")
The following options are exposed by the testcontainers
package.
Basic Options¶
WithExposedPorts
Since v0.37.0WithEnv
Since v0.29.0WithWaitStrategy
Since v0.20.0WithAdditionalWaitStrategy
Not available until the next release mainWithWaitStrategyAndDeadline
Since v0.20.0WithAdditionalWaitStrategyAndDeadline
Not available until the next release mainWithEntrypoint
Since v0.37.0WithEntrypointArgs
Since v0.37.0WithCmd
Since v0.37.0WithCmdArgs
Since v0.37.0WithLabels
Since v0.37.0
Lifecycle Options¶
WithLifecycleHooks
Not available until the next release mainWithAdditionalLifecycleHooks
Not available until the next release mainWithStartupCommand
Since v0.25.0WithAfterReadyCommand
Since v0.28.0
Files & Mounts Options¶
WithFiles
Since v0.37.0WithMounts
Since v0.37.0WithTmpfs
Since v0.37.0WithImageMount
Since v0.37.0
Build Options¶
WithDockerfile
Since v0.37.0
Logging Options¶
WithLogConsumers
Since v0.28.0WithLogConsumerConfig
Not available until the next release mainWithLogger
Since v0.29.0
Image Options¶
WithAlwaysPull
Not available until the next release mainWithImageSubstitutors
Since v0.26.0WithImagePlatform
Not available until the next release main
Networking Options¶
WithNetwork
Since v0.27.0WithNetworkByName
Not available until the next release mainWithBridgeNetwork
Not available until the next release mainWithNewNetwork
Since v0.27.0
Advanced Options¶
WithHostPortAccess
Since v0.31.0WithConfigModifier
Since v0.20.0WithHostConfigModifier
Since v0.20.0WithEndpointSettingsModifier
Since v0.20.0CustomizeRequest
Since v0.20.0WithName
Not available until the next release mainWithNoStart
Not available until the next release main
Experimental Options¶
WithReuseByName
Since v0.37.0
Container Methods¶
The K3s container exposes the following methods:
GetKubeConfig¶
- Since v0.21.0
The GetKubeConfig
method returns the K3s cluster's kubeconfig
, including the server URL, to be used for connecting
to the Kubernetes Rest Client API using a Kubernetes client. It'll be returned in the format of []bytes
.
package k3s_test
import (
"context"
"fmt"
"log"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/k3s"
)
func ExampleRun() {
// runK3sContainer {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
defer func() {
if err := testcontainers.TerminateContainer(k3sContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
// }
state, err := k3sContainer.State(ctx)
if err != nil {
log.Printf("failed to get container state: %s", err)
return
}
fmt.Println(state.Running)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
if err != nil {
log.Printf("failed to get kubeconfig: %s", err)
return
}
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
if err != nil {
log.Printf("failed to create rest config: %s", err)
return
}
k8s, err := kubernetes.NewForConfig(restcfg)
if err != nil {
log.Printf("failed to create k8s client: %s", err)
return
}
nodes, err := k8s.CoreV1().Nodes().List(ctx, v1.ListOptions{})
if err != nil {
log.Printf("failed to list nodes: %s", err)
return
}
fmt.Println(len(nodes.Items))
// Output:
// true
// 1
}
LoadImages¶
- Since v0.25.0
The LoadImages
method loads a list of images into the kubernetes cluster and makes them available to pods.
This is useful for testing images generated locally without having to push them to a public docker registry or having to configure k3s
to use a private registry.
The images must be already present in the node running the test. DockerProvider offers a method for pulling images, which can be used from the test code to ensure the image is present locally before loading them to the cluster.