Author : MD TAREQ HASSAN | Updated : 2023/07/19

What Is Dockerfile?

Layers

Docker builds a container from the Dockerfile (inside image), each step corresponds to a command run in the Dockerfile. And each layer is made up of the file generated from running that command.

Explanation

We usually build a custom image for a container on top of a base image that we get from an official repository like the Docker Hub registry. That is precisely what happens under the covers when you enable Docker support in Visual Studio. Our Dockerfile will use an existing image i.e. mcr.microsoft.com/dotnet/aspnet:5.0 to build docker image. Therefore, we need to specify what base Docker image we will use for our container. We do that by adding FROM mcr.microsoft.com/dotnet/aspnet:5.0 to the Dockerfile.

Dockerfile example

FROM node:current-alpine
COPY . /usr/src/app/
WORKDIR /usr/src/app
RUN npm install && npm run build
EXPOSE 3000
ENTRYPOINT ["npm", "start"]

Explanation

Multi-stage Builds

Multi-stage builds in Dockerfile

Example

#
# Stage 1
#
FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80

#
# Stage 2
#
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["DemoService/DemoService.csproj", "DemoService/"]
RUN dotnet restore "DemoService/DemoService.csproj"
COPY . .
WORKDIR "/src/DemoService"
RUN dotnet build "DemoService.csproj" -c Release -o /app/build

#
# Stage 3
#
FROM build AS publish
RUN dotnet publish "DemoService.csproj" -c Release -o /app/publish

#
# Stage 4
#
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DemoService.dll"]

Explanations

Example 2

FROM golang:1.16 AS builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]

Explanation:

Example 3

# https://hub.docker.com/_/microsoft-dotnet
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY *.sln .
COPY aspnetapp/*.csproj ./aspnetapp/
RUN dotnet restore

# copy everything else and build app
COPY aspnetapp/. ./aspnetapp/
WORKDIR /source/aspnetapp
RUN dotnet publish -c release -o /app --no-restore

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=build /app ./
ENTRYPOINT ["dotnet", "aspnetapp.dll"]

Commands In Dockerfile

Relation of Docker Commands With Image And Container