Search code examples
dockerdockerfileyarnpkg

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?


Solution

  • For those who are still interested in this topic after March 6, 2024.

    You can use --parents flag with COPY instruction. This is available since Dockerfile 1.7.0-labs:

    # syntax=docker/dockerfile:1.7-labs
    

    Note that this is not yet available in stable sytnax, and you need to add # syntax= directive.

    # syntax=docker/dockerfile:1.7-labs
    FROM node:20-alpine AS build
    WORKDIR /app
    COPY --parents packages/*/package.json .
    
    ❯❯❯ docker build --tag foobarimg .
    ❯❯❯ docker run -it foobarimg sh
    /app # find .
    .
    ./packages
    ./packages/foo
    ./packages/foo/package.json
    ./packages/bar
    ./packages/bar/package.json