Search code examples
dockerdockerfiledocker-imagedocker-build

Is there a way to ADD/COPY both directory and file in a single ADD/COPY command (dockerfile)?


In my dockerfile I am trying to ADD/COPY a file and a directory into destinationFolder. Expected output is:

destinationFolder/test.txt
destinationFolder/test_dir/*

However, in the ADD command (as mentioned in note), the directory itself is not copied, just its contents.

ADD test.txt test_dir /destinationFolder/

Is there a way to achieve the desired output using a single ADD/COPY command?


Solution

  • 2 solutions depending on the exact contents of your current project directory. The base line is the same though: have all your contents in the same dir and push the content of that directory directly to a target dir inside your image.

    Moreover, as described in Docker best practice, I suggest you use COPY instead of ADD if you don't need any special functionalities from the latest.

    Move your contents to a separate folder

    All contents you want to push to your destination folder can be placed in a dedicated folder you push at once:

    In your project dir you can

    mkdir imageContents
    mv test.text test_dir imageContents
    

    And you modify your Dockerfile with:

    COPY imageContents destinationFolder/
    

    Replicate the exact structure from your project root

    The idea is the same except you push the root or your project directly to your image. This will also work for any other folder you put there and that is not ignored. Note that you can use this for existing folder structures to simply add some files (like in the /etc/ structure).

    Create a .dockerignore file to make sure you only copy the relevant contents:

    .dockerignore
    Dockerfile
    .git
    # Add any other files that should be out of context
    # Dummy examples below
    .yamllint
    mysecretfiles
    

    Recreate the exact file structure you want to push to your image, in your case:

    mkdir destinationFolder
    mv test.txt test_dir destinationFolder
    

    Eventually add some other files you want to push to your image

    mkdir -p etc/myapp
    echo "config1=myvalue" > etc/myapp/myapp.conf
    

    And modify your Docker file as:

    COPY . /
    

    Make your own method

    You can easily mix the two methods above to fit your exact needs to whatever destination in your image file.