Docker image layers themselves do not have “tags” in the same way that a final Docker image has a tag. 
Tags are applied to the entire image, which is composed of multiple layers. 
However, in multi-stage builds, you can tag the output of specific stages to create intermediate images that can be used or referenced later.

Here’s an example of how you can achieve this in a multi-stage Dockerfile:

# Stage 1: Build the application
FROM node:18-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Create a smaller runtime image
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/build ./build
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
CMD ["npm", "start"]
# Stage 1: Build the application
FROM node:18-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Create a smaller runtime image
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/build ./build
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
CMD ["npm", "start"]

In this example:

  • Stage 1 (builder): This stage builds your application. You can tag the result of this stage as an image if needed, for instance, to inspect the build artifacts or use it as a base for other builds.

To build and tag this specific stage:

docker build --target builder -t my-app-builder:latest .

This command builds only up to the builder stage and tags the resulting image as my-app-builder:latest.

  • Stage 2 (Final Image): This stage takes the necessary build artifacts from the builder stage and creates a smaller, production-ready image.

To build and tag the final image:

docker build -t my-app:latest .

This command builds the entire Dockerfile and tags the final image as my-app:latest.

Key Points:

–target flag:
This flag in docker build allows you to specify which stage in a multi-stage Dockerfile you want to build up to and including tag.
-t or –tag:
The -t (or –tag) is used to assign a name and optional tag (e.g., :latest, :v1.0) to resulting Docker image.
(Remember that individual layers within an image are identifed by their content hash and are part of the image’s history, but only the complete image itself receives a user-defined tag.)

Leave a Reply