docker-compose persistent data on host and container

笑着哭i 提交于 2019-11-28 13:00:51

It sounds like you are using a host volume where you map a host directory into the container. When you do this, anything at that location inside your image will not be visible, only the files as they exist on the host.

If you want to have a copy of the files from inside your image to initialize the volume, you have two options:

  1. Switched to a named volume. Docker will automatically initialize these to the contents of the image, including any permissions. If you don't require direct access to the files from outside of docker, this is the preferred solution.

  2. Change your image entrypoint and the location where you store your files in the image.

On the second option, if you want /data to be a volume for your application, you could have an entrypoint.sh that does:

#!/bin/sh

if [ ! -d "/data" ]; then
  ln -s /data_save /data
elif [ -z "$(ls -A /data)" ]; then
  cp -a /data_save/. /data/
fi
exec "$@"

Your image would need to save all the initial files to /data_save instead of /data. Then if the directory is empty it would do a copy of /data_save to your volume /data. If the volume wasn't mapped at all, then it just creates a symlink from /data to /data_save. The last line runs the CMD from your Dockerfile or docker run cli as if the entrypoint wasn't ever there. The added lines to your Dockerfile would look like:

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!