How to Use Docker Build -t to Tag Images
Use
docker build -t <image_name>:<tag> <path> to build a Docker image and assign it a name and tag in one step. The -t option tags the image, making it easier to identify and run later.Syntax
The docker build -t command has two main parts:
- -t <image_name>:<tag>: Assigns a name and optional tag to the image.
- <path>: Specifies the directory containing the Dockerfile.
This tags the image so you can refer to it easily when running or pushing it.
bash
docker build -t myapp:1.0 ./appExample
This example builds a Docker image named myapp with the tag v1 from the current directory.
bash
docker build -t myapp:v1 .
Output
Sending build context to Docker daemon 2.048kB
Step 1/3 : FROM alpine:latest
---> a24bb4013296
Step 2/3 : RUN echo "Hello from myapp!"
---> Running in 123abc456def
Hello from myapp!
Removing intermediate container 123abc456def
---> 789def012abc
Step 3/3 : CMD ["echo", "Hello from myapp!"]
---> Running in 456def789abc
Removing intermediate container 456def789abc
---> 012abc345def
Successfully built 012abc345def
Successfully tagged myapp:v1
Common Pitfalls
Common mistakes when using docker build -t include:
- Forgetting to specify the build context path (usually
.for current directory). - Using invalid characters in image names or tags.
- Not tagging the image, which creates an untagged image called
<none>.
Always include the -t option with a valid name and tag to avoid confusion.
bash
docker build .
# This builds an image but does not tag it
docker build -t myapp .
# Correct: tags image as 'myapp:latest'Quick Reference
| Option | Description | Example |
|---|---|---|
| -t | Tags the image with name and optional tag | docker build -t myapp:1.0 . |
| Directory containing Dockerfile | docker build -t myapp ./app | |
| Name to identify the image | myapp | |
| Version or label for the image (default is 'latest') | 1.0, v1, latest |
Key Takeaways
Use -t to tag your Docker image with a name and optional version during build.
Always specify the build context path, usually the directory with your Dockerfile.
Tags help you identify and run the correct image easily later.
Avoid invalid characters in image names and tags to prevent errors.
If you omit -t, Docker creates an untagged image which is harder to manage.