Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker COPY files using glob pattern?

I have a monorepo managed by Yarn, I'd like to take advantage of the Docker cache layers to speed up my builds, to do so I'd like to first copy the package.json and yarn.lock files, run yarn install and then copy the rest of the files.

This is my repo structure:

packages/one/package.json packages/one/index.js packages/two/package.json packages/two/index.js package.json yarn.lock 

And this is the interested part of the Dockerfile:

COPY package.json . COPY yarn.lock . COPY packages/**/package.json ./ RUN yarn install --pure-lockfile COPY . . 

The problem is that the 3rd COPY command doesn't copy anything, how can I achieve the expected result?

like image 210
Fez Vrasta Avatar asked Apr 20 '18 10:04

Fez Vrasta


People also ask

How do I copy multiple files from docker container to local machine?

Usage: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH Copy files/folders between a container and the local filesystem Use '-' as the source to read a tar archive from stdin and extract it to a directory destination in a container.

Does docker Copy command Create directory?

Docker Dockerfiles COPY InstructionAll new files and directories are created with a UID and GID of 0.


1 Answers

There is a solution based on multistage-build feature:

FROM node:12.18.2-alpine3.11  WORKDIR /app COPY ["package.json", "yarn.lock", "./"] # Step 2: Copy whole app COPY packages packages  # Step 3: Find and remove non-package.json files RUN find packages \! -name "package.json" -mindepth 2 -maxdepth 2 -print | xargs rm -rf  # Step 4: Define second build stage FROM node:12.18.2-alpine3.11  WORKDIR /app # Step 5: Copy files from the first build stage. COPY --from=0 /app .  RUN yarn install --frozen-lockfile  COPY . .  # To restore workspaces symlinks RUN yarn install --frozen-lockfile  CMD yarn start 

On Step 5 the layer cache will be reused even if any file in packages directory has changed.

like image 185
mbelsky Avatar answered Sep 26 '22 14:09

mbelsky