Docker – ADD Instruction
If you want to extract a TAR file inside a Docker Container or copy files from a URL or local directory, you can specify ADD Instructions inside your Dockerfile. This is different from COPY instruction because COPY instruction only allows you to copy files and directories from the local machine.
In this article, we will see practical examples where you can use ADD instruction to extract a tar file inside your Docker Image.
Step 1: Create a Tar File
For this example, we are simply going to create a TAR file of a folder. You can use this command to create a tar file.
tar -zcvf my-tar-folder.tar.gz ~/Desktop/my-tar-folder
Step 2: Creating the Dockerfile
After you have your Tar file ready, you can now create a Dockerfile with ADD instruction.
FROM ubuntu:latest RUN apt-get -y update ADD my-tar-folder.tar.gz .
In the above Dockerfile, we have pulled the Ubuntu base Image from Docker Hub and updated the Image using an apt-get update. After that, we have included the ADD instruction to extract the TAR file located inside the same directory as that of the Dockerfile.
Step 3: Building the Docker Image
After creating the Dockerfile, you can now create the Docker Image using the Docker build command.
sudo docker build -t sample-image .
To confirm whether the image has been successfully built or not, use the Image list command.
sudo docker images
Step 4: Running the Docker Container
After you have created the Docker Image, you can now run the Docker Container associated with the Docker Image using the Docker Run command.
sudo docker run -it sample-image bash
Step 5: Verifying the Extraction
After you have the bash of the Container running, you can use the list command to list the directories and verify the instruction.