A2oz

How Do I Add a File to a Docker Container?

Published in Docker 3 mins read

You can add a file to a Docker container in a few ways:

1. Using the docker cp Command

The docker cp command is a simple and straightforward way to copy files into a running container.

  • Syntax: docker cp <source> <destination>

  • Example: To copy a file named my_file.txt from your local machine to the /app directory inside a container with the ID container_id, you would use:

     docker cp my_file.txt container_id:/app

2. Mounting a Volume

Volumes provide a persistent way to store data within a Docker container. You can mount a directory from your local machine into the container, allowing you to access the files directly.

  • Syntax: docker run -v <host_path>:<container_path> <image_name>

  • Example: To mount the /data directory from your local machine to the /app directory in a container running the nginx image, you would use:

     docker run -v /data:/app nginx

3. Building the Image with the File Included

If you want to include a file permanently in the container image, you can add it during the image build process using the COPY instruction in your Dockerfile.

  • Syntax: COPY <source> <destination>

  • Example: To copy the my_file.txt file from the current directory to the /app directory in your Docker image, you would add the following line to your Dockerfile:

     COPY my_file.txt /app

    Then, build the image using:

     docker build -t my-image .

4. Using the ADD Instruction

Similar to COPY, the ADD instruction can be used to include a file in the image. However, it can also be used to download files from a URL.

  • Syntax: ADD <source> <destination>

  • Example: To download a file from a URL and add it to the /app directory in your image, you would use:

     ADD https://example.com/my_file.txt /app

    Then, build the image using:

     docker build -t my-image .

Remember: When using volumes or docker cp, changes made to the files within the container will be reflected in the mounted volume or local file, respectively. However, if you add the file during the image build process, the changes will not be reflected in the original file on your local machine.

Related Articles