How to Tag an Image Using Docker and Docker Compose
When creating a Docker image, it is best practice to give it a descriptive and meaningful name. This process makes identifying and managing images more manageable, especially when working with many images.
This article will discuss tagging an image in Docker and Docker Compose.
Tagging an Image in Docker Using Docker Build
Docker doesn’t support tagging an image in the Dockerfile. So instead, we use the docker build
command to tag an image.
To name a Docker image, you use the -t
or --tag
option when running the docker build command.
Example Code:
docker build -t my-image .
In this command, the -t
option specifies the name of the image as my-image
. The name of the image must be unique within the registry where the image is stored.
If we try to build an image with an existing name, the build will fail with an error message.
When naming a Docker image, it is a good idea to use a reverse domain name notation for the name. This is because Docker automatically provides a hierarchical and unique namespace for the image.
For example, if our company’s domain is example.com
, you can name your Docker image com.example.my-image
.
Tagging an Image in Docker Compose YAML File
We could not tag an image in Docker Compose like vanilla Docker. However, the only difference is we can tag the image in the docker-compose.yml
file instead.
Example YML file:
version: "3"
services:
web:
image: my-image:v3
Now, to build the image, we can use the same docker build
command and specify the name and version of the image using the -t
or --tag
option.
Example Code:
docker compose build -t my-image:v3 .
In this command, the -t
option specifies the name and version of the image as my-image:v3
. The period (.
) at the end of the command establishes the build context, and the build context is the directory where we can locate the YAML file inside the system in Docker Compose.
When building the image, Docker Compose reads the YAML file and uses the image instruction to add the specified name and version to the image. We can then use the docker images
command to view the list of tagged images.
Example Code:
docker images
Output:
REPOSITORY TAG IMAGE ID CREATED SIZE
my-image v3 abc123 9 days ago 1GB
Overall, giving a descriptive and meaningful name to a Docker image is essential for ease of identification and management. Using the reverse domain name notation and tags can help you create a hierarchical and unique namespace for your image and allow you to identify different versions of your image quickly.
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn