0
0
Dockerdevops~5 mins

Tagging images during build in Docker - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you build a Docker image, you want to give it a name and a version so you can find and use it later. Tagging images during build helps you label your images clearly, so you know what they are and which version they are.
When you want to save a specific version of your app image to use later or share with others.
When you need to run multiple versions of the same app on your machine or server.
When you want to push your image to a registry with a clear name and version.
When you want to avoid confusion between different builds of your app.
When you want to automate builds and keep track of image versions in CI/CD pipelines.
Commands
This command builds a Docker image from the current folder (.) and tags it with the name 'my-app' and version '1.0'. The -t flag sets the tag.
Terminal
docker build -t my-app:1.0 .
Expected OutputExpected
Sending build context to Docker daemon 2.048kB Step 1/3 : FROM alpine:3.18 3.18: Pulling from library/alpine Digest: sha256:... Status: Downloaded newer image for alpine:3.18 ---> 3f53bb00af94 Step 2/3 : RUN echo "Hello, Docker!" ---> Running in 123abc456def Removing intermediate container 123abc456def ---> 789xyz123uvw Step 3/3 : CMD ["echo", "Hello, Docker!"] ---> Running in 456def789abc Removing intermediate container 456def789abc ---> 321uvw654xyz Successfully built 321uvw654xyz Successfully tagged my-app:1.0
-t - Assigns a name and optionally a tag in the 'name:tag' format to the image.
This command lists all Docker images with the name 'my-app' so you can see the tagged image you just built.
Terminal
docker images my-app
Expected OutputExpected
REPOSITORY TAG IMAGE ID CREATED SIZE my-app 1.0 321uvw654xyz 10 seconds ago 5.6MB
This runs the Docker image tagged 'my-app:1.0' to verify it works as expected. The --rm flag removes the container after it stops.
Terminal
docker run --rm my-app:1.0
Expected OutputExpected
Hello, Docker!
--rm - Automatically removes the container when it exits to keep your system clean.
Key Concept

If you remember nothing else from this pattern, remember: use the -t flag during docker build to give your image a clear name and version tag.

Common Mistakes
Building the image without the -t flag and then trying to run it by name.
Without a tag, the image has no name, so you cannot easily find or run it by name.
Always use the -t flag with a name and tag when building images to identify them.
Using a tag with spaces or invalid characters.
Docker tags must not contain spaces or special characters, causing build errors.
Use only letters, numbers, dots, dashes, and underscores in tags.
Summary
Use 'docker build -t name:tag .' to build and tag your image in one step.
Check your tagged images with 'docker images name' to confirm the tag.
Run your tagged image with 'docker run name:tag' to test it.