Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy file from host to container using Dockerfile

I have written a Dockerfile which looks like this

FROM ubuntu:12.04  RUN apt-get update RUN apt-get install -y wget 

Now I'm having a file called abc.txt in my host machine. How can I copy it to this container. Is there any step that I can add in Dockerfile which copy from Host to Container.

like image 393
Sasikiran Vaddi Avatar asked May 26 '15 09:05

Sasikiran Vaddi


People also ask

Can I copy files from host machine to Docker container?

The Docker cp command can be used to copy files and directories from the host machine to a container and vice-versa.

How do I copy a file into a Docker container?

To summarize, follow these steps to copy a file from a Docker container to a host machine: Obtain the name or id of the Docker container. Issue the docker cp command and reference the container name or id. The first parameter of the docker copy command is the path to the file inside the container.

Which Dockerfile command defines files to copy from the host file system onto the container?

Docker cp Command It can only be used to copy files between the host system and a single container.


2 Answers

Use COPY command like this:

COPY foo.txt /data/foo.txt # where foo.txt is the relative path on host # and /data/foo.txt is the absolute path in the image 

read more details for COPY in the official documentation

An alternative would be to use ADD but this is not the best practise if you dont want to use some advanced features of ADD like decompression of tar.gz files.If you still want to use ADD command, do it like this:

ADD abc.txt /data/abc.txt # where abc.txt is the relative path on host # and /data/abc.txt is the absolute path in the image 

read more details for ADD in the official documentation

like image 77
george.yord Avatar answered Sep 28 '22 06:09

george.yord


For those who get this (terribly unclear) error:

COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory

There could be loads of reasons, including:

  • For docker-compose users, remember that the docker-compose.yml context overwrites the context of the Dockerfile. Your COPY statements now need to navigate a path relative to what is defined in docker-compose.yml instead of relative to your Dockerfile.
  • Trailing comments or a semicolon on the COPY line: COPY abc.txt /app #This won't work
  • The file is in a directory ignored by .dockerignore or .gitignore files (be wary of wildcards)
  • You made a typo

Sometimes WORKDIR /abc followed by COPY . xyz/ works where COPY /abc xyz/ fails, but it's a bit ugly.

like image 20
Overleaf Avatar answered Sep 28 '22 06:09

Overleaf