Image
Creating an image
A dockerfile contains the instructions needed to build a suitable operating system to run an application.
Sample
FROM node AS build
WORKDIR /client
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn run build
FROM nginx:stable-alpine
COPY --from=build /client/dist /usr/share/nginx/html
COPY --from=build /client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
The sample shows steps taken to build and deploy a
React
application. This dockerfile is optimized to use multi-stage builds and leverage layer cache.
Layer Cache
FROM node AS build
WORKDIR /client
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn run build
FROM nginx:stable-alpine
COPY --from=build /client/dist /usr/share/nginx/html
COPY --from=build /client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Each instruction in this Dockerfile translates to a layer in your final image. Whenever a layer changes, that layer will need to be re-built.
The dependencies from package.json
are installed before copying the rest of the code over because dependencies do not change that often. Read more
Multi-stage builds
FROM node AS build
WORKDIR /client
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn run build
FROM nginx:stable-alpine
COPY --from=build /client/dist /usr/share/nginx/html
COPY --from=build /client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
You use multiple FROM
statements for each new stage of the build and you can selectively copy artifacts from another stage. This leads to a smaller final image size. Read more
Building an Image
docker build -t <image_name> .
The last argument specifies where the dockerfile is. In this example, it is in the current directory
.
.