"Retrieving a Lost Docker Image Tag from a k3s Cluster and Pushing it to Container Registry"

Use Case

If your docker image tag has been mistakenly deleted from Gitlab Container Registry and you do have it on the k3s cluster on any server. Then you can push that image to GitLab by following this guide.

It is important to note that the commands given below will only work if the user executing the script has the appropriate permissions to access the k3s cluster, export and import images, and push images to the specified Gitlab repository.

Step 1:

List all images in a specific namespace and filter for the desired image:

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n <namespace> i ls | grep <repository_url>:<tag>

Example:

This command will list all the images in the k8s.io namespace and then use grep to filter for the specific image with the repository URL gitlab.com/gitlab-org/project-templates/spring and tag 1.0.

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n k8s.io i ls | grep gitlab.com/gitlab-org/project-templates/spring:1.0

Step 2 :

Export the desired image to a tar file:

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n <namespace> i export <filename.tar> <repository_url>:<tag>

Example:

This command will export the image found in the previous command to a tar file named my-spring-app.tar.

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n k8s.io i export my-spring-app.tar gitlab.com/gitlab-org/project-templates/spring/build:1.0

Step 3 :

Import the tar file into a specific namespace:

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n <import_namespace> i import <filename.tar>

Example:

This command is importing the tar file created in the previous step into a namespace named 'dev'.

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n dev i import my-spring-app.tar

Step 4 :

Push the imported image to a GitLab repository:

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n <import_namespace> i push -u <username:password> --platform <platform> <repository_url>:<tag>

Example:

This command is pushing the imported image to the GitLab repository with the specified username and password and specifies the platform as Linux/amd64.

CONTAINERD_ADDRESS=/run/k3s/containerd/containerd.sock ctr -n dev i push -u username:password --platform linux/amd64 gitlab.com/gitlab-org/project-templates/spring:1.0

Ending Note

The above commands are using ctr(containerd client) to interact with the k3s cluster and containerd, ctr is a command-line tool for interacting with containerd. It allows you to manage images, containers, and other resources that containerd manages, it also allows you to interact with the containerd API.

Happy Learning !