Dockerfile - only copy files which match an extension whilst maintaining folder structure

Viewed 412

Suppose I have a very nested folder structure with lots of project files:

src
  projectA
    projectA.csproj
    someFile.txt
  projectB
    projectB.csproj
    someFile.txt
  projectC
    projectC.csproj
    someFile.txt

In this case I want my DockerFile to copy over the full folder structure, but only include .csproj files:

src
  projectA
    projectA.csproj
  projectB
    projectB.csproj
  projectC
    projectC.csproj

I can do this for each file line by line, but is there a cleaner way?

COPY src/projectA/projectA.csproj src/projectA/projectA.csproj
COPY src/projectB/projectB.csproj src/projectB/projectB.csproj
COPY src/projectC/projectC.csproj src/projectC/projectC.csproj
1 Answers

I've faced a similar situation and the only solution I've found was to prepare a .tgz file containing what I needed and copy it in the docker image using the ADD directive.

e.g. this is a run.sh script similar to what I used:

#!/bin/bash

tar cvfz csproj.tgz $( find src -name "*.csproj" )
docker build -t test .
docker run -it --rm test

this is a test Dockerfile:

FROM alpine
RUN mkdir /src
ADD csproj.tgz /src
CMD ls -alR /src

This solution is not very pleasant but it did do what I needed at the time.

The ADD directive (src: https://docs.docker.com/engine/reference/builder/#add) is able to copy files (like the COPY directive) and

If is a local tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from remote URLs are not decompressed.

Related