`docker cp` doesn't copy file into container

2019-07-08 08:03发布

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:/#

标签: docker
3条回答
该账号已被封号
2楼-- · 2019-07-08 08:21

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.

查看更多
狗以群分
3楼-- · 2019-07-08 08:33

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))'

查看更多
戒情不戒烟
4楼-- · 2019-07-08 08:44

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
查看更多
登录 后发表回答