dockerdockerfiledocker-copy

Why Is This File Copied to the Root of a Docker Image Instead of the Working Directory


Using the following Dockerfile:

FROM alpine:latest

WORKDIR /usr/src/app

COPY ["somefile", "/"]

and the build following command:

docker build \
--file=Dockerfile \
--no-cache=true \
--progress=plain \
--tag=someimage:sometag \
.

=>

#1 [internal] load build definition from Dockerfile
. . .
#8 naming to docker.io/someimage:sometag done
#8 DONE 0.0s

why is somefile found at the root (/):

docker run someimage:sometag ls -altr ../../../.

#=>

total 68
. . .
-rw-r--r--    1 root     root           128 Jul 27 12:34 somefile
. . .
drwxr-xr-x    1 root     root          4096 Jul 27 12:34 ..
drwxr-xr-x    1 root     root          4096 Jul 27 12:34 .

and not the working directory (/usr/src/app):

docker run someimage:sometag ls -altr .

#=>

total 8
drwxr-xr-x    3 root     root          4096 Jul 27 12:34 ..
drwxr-xr-x    2 root     root          4096 Jul 27 12:34 .

Solution

  • The COPY instruction in your Dockerfile:

    . . .
    COPY ["somefile", "/"]
    . . .
    

    uses an absolute path instead of a relative path; more on that here.

    Replacing / with ./ will COPY somefile to /usr/src/app instead of the root dir:

    FROM alpine:latest
    
    WORKDIR /usr/src/app
    
    COPY ["somefile", "./"]
    
    

    We can locate somefile after we build the image with:

    docker run someimage:anothertag ls -altr .
    
    #=>
    
    total 16
    -rw-r--r--    1 root     root           128 Jul 27 23:45 somefile
    drwxr-xr-x    1 root     root          4096 Jul 27 23:45 ..
    drwxr-xr-x    1 root     root          4096 Jul 27 23:45 .