Dockerfile copy keep subdirectory structure

CopyDockerDockerfile

Copy Problem Overview


I'm trying to copy a number of files and folders to a docker image build from my localhost.

The files are like this:

folder1
    file1
    file2
folder2
    file1
    file2

I'm trying to make the copy like this:

COPY files/* /files/

However, all files are placed in /files/ is there a way in Docker to keep the subdirectory structure as well as copying the files into their directories?

Copy Solutions


Solution 1 - Copy

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

Solution 2 - Copy

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

Solution 3 - Copy

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./local-path/. /image-path/

Solution 4 - Copy

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1220022View Question on Stackoverflow
Solution 1 - CopyISanychView Answer on Stackoverflow
Solution 2 - CopySparkz0629View Answer on Stackoverflow
Solution 3 - CopyCameron HudsonView Answer on Stackoverflow
Solution 4 - CopyDileep JayasundaraView Answer on Stackoverflow