简体   繁体   中英

`docker cp` doesn't copy file into container

I have a dockerized project. I build, copy a file from the host system into the docker container, and then shell into the container to find that the file isn't there. How is docker cp supposed to work?

$ docker build -q -t foo .
Sending build context to Docker daemon    64 kB
Step 0 : FROM ubuntu:14.04
 ---> 2d24f826cb16
Step 1 : MAINTAINER Brandon Istenes <redacted@email.com>
 ---> Using cache
 ---> f53a163ef8ce
Step 2 : RUN apt-get update
 ---> Using cache
 ---> 32b06b4131d4
Successfully built 32b06b4131d4
$ docker cp ~/.ssh/known_hosts foo:/root/.ssh/known_hosts
$ docker run -it foo bash
WARNING: Your kernel does not support memory swappiness capabilities, memory swappiness discarded.
root@421fc2866b14:/# ls /root/.ssh
root@421fc2866b14:/#

So there was some mix-up with the names of images and containers. Obviously, the cp operation was acting on a different container than I brought up with the run command. In any case, the correct procedure is:

# Build the image, call it foo-build
docker build -q -t foo-build .

# Create a container from the image called foo-tmp
docker create --name foo-tmp foo-build

# Run the copy command on the container
docker cp /src/path foo-tmp:/dest/path

# Commit the container as a new image
docker commit foo-tmp foo

# The new image will have the files
docker run foo ls /dest

You need to docker exec to get into your container, your command creates a new container.

I have this alias to get into the last created container with the shell of the container

alias exec_last='docker exec -it $(docker ps -lq) $(docker inspect -f {{'.Path'}} $(docker ps -lq))'

What docker version are you using? As per Docker 1.8 cp supports copying from host to container:

• Copy files from host to container: docker cp used to only copy files from a container out to the host, but it now works the other way round: docker cp foo.txt mycontainer:/foo.txt

Please note the difference between images and containers. If you want that every container that you create from that Dockerfile contains that file (even if you don't copy afterward) you can use COPY and ADD in the Dockerfile. If you want to copy the file after the container is created from the image, you can use the docker cp command in version 1.8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM