Docker is a virtualisation tool. It can create lightweight, fast, isolated, and reproducible environments like virtual machines, in which an application can be tested reliably.
An docker image is a snapshot of an operating system. A container is an instance of an image, behaving like a running virtual machine.
Testing Process#
Say I want to test a rust project with file structure like
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
└── debugIn a brand new operating system, everything needed to test this project is the rust-cargo suite, besides the source code. So I want the container to have them.
All containers must be built from an image.
Custom images can be built from a Dockerfile.
The dockerfile for our purpose is
# Dockerfile
FROM rust:1.86 # we build our image from the official rust image available on docker hub
WORKDIR /app # set working directory to /app
COPY . . # copy all files in current directory to /app in the containerTo build the image, run
docker build -t <image_name> .
docker images # list all images. You may see several images, as we have pulled one from Docker HubTo instantiate a container, run
docker run -it <image_name> /bin/bash # run the containter interactively in command modeThe expected output is an interactive bash shell prompt running in the container in the directory /app, in which all of the source codes are present.
Now just test the project as usual.
Docker Hub and other Registries for container#
To test rust, we build our custom image from the official rust image on Docker Hub. There are plethora of images on Docker Hub for testing other applications, including python, nodejs, golang, debian, ubuntu, nginx, postgres, etc.
Many other image registries exist, for example, there are gcr.io, quay.io, etc.
To pull those image, simple use their url in Dockerfile, eg.
from quay.io/capk/ubuntu-2404-container-disk:v1.32.1Images can also be pulled onto your local machine independently of a Dockerfile
docker pull quay.io/capk/ubuntu-2404-container-disk:v1.32.1Images pulled this way have a very long name. Tag them for convenience.
docker tag quay.io/capk/ubuntu-2404-container-disk:v1.32.1 my_ubuntu:latestAnd now the Dockerfile can be written as
FROM my_ubuntu:latestIn China#
Docker Hub is blocked in China.
Instead, search images on aityp.
For example swr.cn-north-4.myhuaweicloud.com/ddn-k8s/quay.io/capk/ubuntu-2404-container-disk:v1.32.1 is the chinese mirror of quay.io/capk/ubuntu-2404-container-disk:v1.32.1.
Dockerfile for Automation#
Dockerfile is extremely powerful. It can be used to automate the testing process.