Just Khaithang
Just Khaithang

Reputation: 1545

How to access files in host from a Docker Container?

I have a Docker Ubuntu Bionic container on A Ubuntu server host. From the container I can see the host drive is mounted as /etc/hosts which is not a directory.

Tried unmounting and remounting on a different location but throws permission denied error, this happens when I am trying as root.

So How do you access the contents of your host system ?

Upvotes: 49

Views: 103636

Answers (4)

Ram
Ram

Reputation: 141

run this command for linking local folder to docker container

docker run -it -v "$(pwd)":/src  centos

pwd: present working directroy(we can use any directory) and

src: we linking pwd with src

Upvotes: 3

quine9997
quine9997

Reputation: 834

Example. container id: 32162f4ebeb0

#HOST BASH SHELL

docker cp 32162f4ebeb0:/dir_inside_container/image1.jpg /dir_inside_host/image1.jpg


docker cp /dir_inside_host/image1.jpg  32162f4ebeb0:/dir_inside_container/image1.jpg 


Upvotes: 18

David Maze
David Maze

Reputation: 158908

Docker directly manages the /etc/hosts files in containers. You can't bind-mount a file there.

Hand-maintaining mappings of host names to IP addresses in multiple places can be tricky to keep up to date. Consider running a DNS server such as BIND or dnsmasq, or using a hosted service like Amazon's Route 53, or a service-discovery system like Consul (which incidentally provides a DNS interface).

If you really need to add entries to a container's /etc/hosts file, the docker run --add-host option or Docker Compose extra_hosts: setting will do it.

As a general rule, a container can't access the host's filesystem, except to the extent that the docker run -v option maps specific directories into a container. Also as a general rule you can't directly change mount points in a container; stop, delete, and recreate it with different -v options.

Upvotes: 3

JShorthouse
JShorthouse

Reputation: 1670

Firstly, etc/hosts is a networking file present on all linux systems, it is not related to drives or docker.

Secondly, if you want to access part of the host filesystem inside a Docker container you need to use volumes. Using the -v flag in a docker run command you can specify a directory on the host to mount into the container, in the format:

-v /path/on/host:/path/inside/container

for example:

docker run -v /path/on/host:/path/inside/container <image_name>

Upvotes: 68

Related Questions