Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit Docker container files from the host?

Tags:

docker

Now that I found a way to expose host files to the container (-v option) I would like to do kind of the opposite:

How can I edit files from a running container with a host editor?

sshfs could probably do the job but since a running container is already some kind of host directory I wonder if there is a portable (between aufs, btrfs and device mapper) way to do that?

like image 904
ascobol Avatar asked Jul 03 '14 12:07

ascobol


People also ask

Can I edit code in docker container?

The Remote – Containers extension for Visual Studio Code lets you edit files and folders inside Docker containers. It works seamlessly with the VS Code editor features, including IntelliSense, directory indexing, debugging, and extensions.

Can docker container access files on host?

Docker provides two ways for containers to save files on the host system so that the files are persistent even after the container is shut down. These are Docker volumes and bind mounts. This blog will teach you how to share data between a Docker containerized application and the host computer.


2 Answers

The best way is:

  $ docker cp CONTAINER:FILEPATH LOCALFILEPATH
  $ vi LOCALFILEPATH
  $ docker cp LOCALFILEPATH CONTAINER:FILEPATH

Limitations with $ docker exec: it can only attach to a running container.

Limitations with $ docker run: it will create a new container.

like image 190
zhigang Avatar answered Oct 22 '22 04:10

zhigang


Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can.

Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do:

$ docker run --name="test" -v /volume-test debian echo "test"

The directory /volume-test inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with:

$ docker inspect -f "{{.Volumes}}" test
map[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895]

If you really need to just make a quick edit to a file to test something, either use docker exec to get a shell in the container and edit directly, or use docker cp to copy the file out, edit on the host and copy back in.

like image 21
Adrian Mouat Avatar answered Oct 22 '22 02:10

Adrian Mouat