vinayan
vinayan

Reputation: 1637

Docker Image from Build Directory vs Source directory

Most of the DockerFiles seem to be generating the image from the source code directory. Is there a reason why this is done?

For example, If I run the build commands in a windows machine and copy the dist folder into a linux machine and run as per Option 2, isn't it supposed to work?

Option 1 - Docker file (from source directory)

FROM node:latest as build    
WORKDIR /usr/local/app    
COPY ./ /usr/local/app/    
RUN npm install    
RUN npm run build    
FROM nginx:latest    
COPY --from=build /usr/local/app/dist /usr/share/nginx/html    
EXPOSE 80

Option 2 - Dockerfile from build output

FROM nginx:latest    
COPY dist /usr/share/nginx/html    
EXPOSE 80

Upvotes: 0

Views: 1029

Answers (1)

David Maze
David Maze

Reputation: 159830

Your first form uses a Docker multi-stage build. This has the specific advantage of not depending on any particular tools being installed on the host system. I'd consider this path:

  • If you have a clustered CI system, it can be much easier to run the build in a container than to try to get the required tools manually installed on every worker system.
  • If you're working in a compiled language (C, Go, Rust, ...), you can consistently use Linux containers even if developers use a different host OS.
  • If you need to do extra work to set up the build system, like installing extra C development packages.
  • If you need a really exact version of the language runtime for whatever reason.

The second path depends on having the toolchain available outside the container environment. That's not necessarily a problem; most front-end developers will probably have Node installed anyways. I'd consider this path:

  • If the result of the build is extremely portable across environments (compiled HTML and Javascript; Java .jar files; interpreted text-format Python or Ruby scripting code).
  • If there aren't big differences in different versions of the language runtime itself to produce the build. (Does your Webpack build do anything different on Node 8, 10, 12, or 14?)
  • If the build system is something that's easy to install, or preinstalled in most host environments. (Most Linux and MacOS systems have Python, for example.)
  • If a host build system can do incremental builds or otherwise run much faster than a clean-slate container build.

For what you show, with a simple front-end application that's compiled to static files, your second form is just fine. If you look at SO Java questions they almost universally COPY a prebuilt .jar file into an image, without including a build chain.

Upvotes: 1

Related Questions