Search code examples
dockerdockerfile

how to copy folders from my linux machine to a docker container?


FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive 
RUN apt-get update
WORKDIR /home/
RUN mkdir folder1
COPY /home/folder1/* /home/folder1
RUN mkdir folder2
COPY /home/folder2/* /home/folder2

I have written the above to copy 2 folders from my pc to a docker container using this dockerfile. I am giving the correct path of folders from source. Dockerfile and folders to be copied and Dockerfile are present on the same level but I am getting this error

=> ERROR [5/7] COPY /home/folder1/* /home/folder1                       0.0s 
------                                                                          
 > [5/7] COPY /home/sushant/jetson/* ./jetson:                                  
------                                                                          
Dockerfile:6
--------------------
   4 |     WORKDIR /home/
   5 |     RUN mkdir jetson
   6 | >>> COPY /home/folder1/* /home/folder1
   7 |     RUN mkdir cuda
   8 |     COPY /home/folder2/* /home/folder2
--------------------
ERROR: failed to solve: lstat /var/lib/docker/tmp/buildkit-mount2125610381/home/folder1: no such file or directory

Solution

  • The left-hand side of a COPY directive is always relative to the build context, the directory you passed as the argument to docker build or named in a docker-compose.yml file. For example, if you do the very common

    docker build .
    

    then even though they look like absolute paths, the /home/folder1 on the left-hand side is actually interpreted as relative to the current directory ..

    In another answer you note that the Dockerfile, folder1, and folder2 are all in the same directory, again a typical setup. In this case you need to use a relative path on the left-hand side of COPY

    FROM ubuntu:20.04
    WORKDIR /home
    COPY ./folder1/* /home/folder1/
    COPY ./folder2/* /home/folder2/
    

    I tend to also use a relative path (relative to WORKDIR) on the right-hand side of COPY as well. COPY creates the destination directory if needed and so you do not need to RUN mkdir.