Introduction
This hands-on lab is designed to provide practical experience with labeling Docker containers and images. Labels are a powerful feature in Docker that allows you to attach metadata to your Docker objects, making it easier to manage, organize, and query your containers and images. Through this lab, you'll learn how to apply labels to Docker images and containers and how to utilize these labels for management and querying purposes.
Objectives
Lab Steps
Step 1: Preparing Your Environment
docker --version in your terminal.Step 2: Creating a Dockerfile with Labels
mkdir labeled-docker-app
cd labeled-docker-app
nano Dockerfile.# Base image
FROM nginx:latest
# Adding labels
LABEL org.example.version="0.1" \
org.example.description="This is a labeled custom Nginx image."
CTRL+O, Enter, CTRL+X).Step 3: Building Your Labeled Image
docker build -t labeled-nginx .
docker inspect labeled-nginx.Step 4: Running a Container with Additional Labels
docker run -d --name my-labeled-nginx --label "org.example.environment=development" labeled-nginx
docker inspect my-labeled-nginx
You should see something like this in the output:
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>",
"org.example.description": "This is a labeled custom Nginx image.",
"org.example.environment": "development",
"org.example.version": "0.1"
},
Step 5: Querying Containers by Labels
Use the Docker CLI to filter and list containers by their labels:
docker ps --filter "label=org.example.environment=development"
This command should list your my-labeled-nginx container.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be6ba8ac786b labeled-nginx "/docker-entrypoint.…" 2 minutes ago Up About a minute 80/tcp my-labeled-nginx
Summary
In this lab, you've gained hands-on experience with Docker's labeling feature, learning how to apply labels to both images and containers. You've created a Dockerfile with embedded labels, built a labeled image, and run a container with additional labels applied at runtime. Finally, you practiced querying and filtering Docker objects based on their labels, demonstrating the power and flexibility of labels for managing Dockerized environments. Understanding and utilizing labeling effectively is key to organizing and automating tasks in complex Docker deployments, enhancing your Docker management capabilities.