Building and naming images well is the bridge between your code and anything you deploy.
docker build -t myapp:1.0 . builds an image from the Dockerfile in the current directory and tags it myapp:1.0.
The final . is the build context: the set of files the builder may access. COPY paths are relative to it, and nothing outside it can be copied (COPY ../secret . fails). With modern Docker the build runs in BuildKit, which transfers only the files the build actually uses, but large contexts still slow builds; that's what .dockerignore is for.
Useful options:
-f docker/Dockerfile.prod: use a Dockerfile elsewhere or with another name.-tcan be repeated:-t myapp:1.4.2 -t myapp:1.4 -t myapp:latest.--build-arg VERSION=1.4.2: pass a value to anARGinstruction.--no-cache: rebuild every step from scratch.--progress=plain: full, unabridged output, handy when debugging a failingRUN.
Tagging strategy matters once images leave your laptop. Tag every build with something immutable and traceable, such as a semantic version (1.4.2) or the git commit (git-3f9a2c1), and optionally move convenience tags (1.4, latest) along. Deploy the immutable tag, so you always know exactly what's running and can roll back.
docker tag adds names after the fact: docker tag myapp:1.4.2 registry.example.com/team/myapp:1.4.2 prepares an image for pushing to a registry. Run the result with docker run myapp:1.4.2.
Example
docker build -t myapp:dev .
docker build -f docker/Dockerfile.prod \
--build-arg VERSION=1.4.2 \
-t myapp:1.4.2 -t myapp:git-$(git rev-parse --short HEAD) .
docker image ls myapp
# myapp 1.4.2 5e1c0a7b9d2f ...
# myapp git-3f9a2c1 5e1c0a7b9d2f ... <- same image ID
docker run --rm -p 8000:8000 myapp:1.4.2
docker build --no-cache --progress=plain -t myapp:debug .Remember
- The trailing . is the build context; COPY can't reach outside it
- -t can be given several times; tags are just names for one image ID
- Deploy immutable tags (version or commit), not latest
Watch out for
- Running docker build from your home directory with . as context, making Docker scan thousands of unrelated files.