Abhijith
Abhijith

Reputation: 2642

How to copy a file to a Docker container before starting/running it?

I'm starting with a docker image that is already built. I would like to do this

  1. Create a docker container from this image. (Don't start)
  2. Copy a file to this container
  3. Start the container

How can this be achieved. It looks like if i run the following commands the file doesn't end up in the container

  1. docker create --name my_container my_image
  2. docker cp file my_container:/tmp/file
  3. docker start my_container

Any idea how this can be achieved ?

Upvotes: 19

Views: 16852

Answers (5)

Glen Whitney
Glen Whitney

Reputation: 601

As far as I can tell, the OP's original proposed sequence of commands only doesn't work because the container is not started yet at the time of the docker cp. Specifically, I have had success with the following sequence of commands to build an image, start a container from that image, copy a file to the new container, and then run a command in the new container, without having to commit/create another image that has the additional desired files:

docker build -q -t my_image .
docker run --name my_container -d -i -t my_image /bin/sh  # dummy to keep container alive
docker cp file my_container:/tmp/file
docker exec -i -t my_container ls /tmp  # or whatever command desired
# Could repeat with file2, file3, etc.
# When done, don't forget to:
docker stop my_container
# And optionally
docker rm my_container

Upvotes: 0

de5tro
de5tro

Reputation: 29

Doesn't exactly answer the question, but can also mount the desired file to the container. The file will be created inside the container if non-existent or will be replaced if existing in the docker container.

Upvotes: 0

Juan Diego
Juan Diego

Reputation: 1466

I have used this option but I do not recommend this for production, you can mount it as an external volume like -v /path/yourlocalfolder:/path/inside/container, this works for files or folders.

Upvotes: 0

Siddharth Kumar
Siddharth Kumar

Reputation: 1

Create a dir (e.g. init) put your sql or shell script in it. bind mount the dir ~/init:/docker-entrypoint-initdb.d/

Upvotes: 0

JesusTinoco
JesusTinoco

Reputation: 11828

You will have to create a new image from a Dockerfile that inherit from the one that is already built, and the use the COPY tag:

Dockerfile

FROM my_image
COPY file /tmp/file

Finally, build that new Dockerfile:

$ docker build -t new_image .

Upvotes: 14

Related Questions