Advanced docker build technique

Advanced usage of docker build

Usage of Dockerignore

  • Basically, docker build loads all sub directories which cause heavy overhead.
    • If there are lots of sub directories, build needs a lot of time to load all data.
    • We need to ignore unnecessary directories to reduce loading time.
  • .dockerignore prevents to load some files and directories.
    • Basically, we can describe original names of files or directories, but it supports some advanced description technique.
    • build means a simple directory name form.
    • */temp* describes directories started with temp inside 1-level sub-directories.
      • For example, log/temp will be ignored from building context.
    • */*/temp* similarly describes directories started with temp inside 2-level sub-directories.
    • temp? means all directories named by 5 characters started with temp.
      • For example, there are tempa , tempb and so on.
# comment
build
*/temp*
*/*/temp*
temp?

Separating building image from production image

  • In Dockerfile script, I have described a way to build an image by Dockerfile.
    • When building docker images, we uses unnecessary packages in production environment.
      • Therefore, we need to remove the redundant files.
    • We can separate production deployment images from build images.
  • I have named a building image to build by as build.
    • Similarly, if you need lots of different building environments, you can define multiple environments named by different one.
  • In building production image, I could have access to build image by --from={{name}}.
    • At this, I checked that golang:latest image was based on debian:buster, therefore I used the same image for production build.
    • As I’ve mentioned, we can copy files from multiple environments defined in advance.
FROM golang:latest as build

ADD . /workdir

WORKDIR /workdir
RUN go build -o app

FROM debian/buster
WORKDIR /app
COPY --from=build /workdir/app /app/app

CMD ["/app/app"]