Skip to content
Advertisement

Creating a symbolic in shared volume of docker and accessing it in host machine

I am creating a symbolic link in mounted volume of a host machine inside a docker. But I am unable to access it in host machine. Is it possible to do it. If yes how can I do that.

I used the following command to mount directory

docker run -it --rm --net host -v $(pwd):/workspace --name myproject my-container:dev

Then I created a symbolic link using

import os
fname = '/workspace/log/project_info_hostinfo_timeinfo_exe_param.log'
symlink_name = '/workspace/log/project_info.log'
os.symlink(fname, symlink_name)

Now when I am trying to see log info it looks like

$ls
lrwxrwxrwx 1 root root   66 Mar  4 14:54 project_info.log -> /workspace/log/project_info_hostinfo_timeinfo_exe_param.log
-rw-r--r-- 1 root root  206 Mar  4 14:54 project_info_hostinfo_timeinfo_exe_param.log

But when I try to open file I got message like

$tail -f project_info.log
tail: cannot open 'project_info.log' for reading: No such file or directory
tail: no files remaining

Advertisement

Answer

You can create a symbolic link with any path name you want. When you access this, it’s used as a normal filesystem path in its own context; if it’s a relative path, it’s accessed relative to the location of the link. If you have the same filesystem in multiple contexts (a bind-mounted Docker directory in both the host and a container; a remote filesystem) it’s possible a symlink will resolve correctly in one context but not the other.

In your example:

  1. The symlink points at the absolute path /workspace/log/project_info_hostinfo_timeinfo_exe_param.log
  2. Inside the container, the /workspace directory is the mounted host directory, so it works
  3. Outside the container, there is no /workspace directory, so it doesn’t work

Also in your example, the link and its target are in the same directory. This means that if the link target is just a filename, it will be looked up in the same directory as the link. That avoids the problem of the absolute paths being different.

import os
# If the link target is in the same directory, just use a filename,
# not an absolute path
fname = 'project_info_hostinfo_timeinfo_exe_param.log'
symlink_name = '/workspace/log/project_info.log'
os.symlink(fname, symlink_name)

It’s often helpful to create a symlink as a relative path to avoid problems with relocating directory trees; ln -s ../assets/index.html ., for example, will still point at the same place even if it’s in a container context or your colleague has a different directory structure on their workstation.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement