Search code examples
dockerdocker-container

How to Copy and Extract a .tar file inside a Docker Container


I'm having a scenario wherein I need to copy a .tar file into docker container and extract the content to a specific folder inside the container. So do we have any specific commands to handle this Scenario?


Solution

  • There are a few options, depending on your exact use case:

    1. COPY directive inside Dockerfile

    See documentation, this command allows you to, well, copy the file from host into your image into specified path. So every time a new container is up, it will be there (obviously, as it's part of the image).

    2. Mounting a volume

    If you want to pass your .tar file into specific container you could mount the volume coming from your host (or create one explicitly using docker volume create from your CLI) using --mount or -v commands like this:

    $ docker run \
      --name mycontainer \
      --mount source=/path/to/folder/containing/tar/file,target=/target \
      myimage
    

    After this operation /path/to/folder/containing/tar/file will be available to container under /target, so you can use the file via path /target/myfile.tar

    I would advise for this option, as this is the more tunable approach.