docker volumes file but create directory

Problems encountered

The docker image will generate new files during the running process. I want to mount this new file in the container to the host computer for easy viewing and preservation. The writing method in docker-compose.yml is as follows:

volumes:
  - ./sample.txt:/code/sample.txt
  # sample.txt是运行生成的新文件。/code是它在容器中的路径

Then two folders sample.tex were generated as a result, respectively on the host and in the container, which caused the program to fail to run normally afterwards

The cause of the problem

When the container starts, if there are no mounted files in the container and the host, a folder will be generated by default

The above is how docker handles the appealed mounting problem, because the new file is generated during the running process, and the host does not have a corresponding file, so the result is normal

solution

1. Generate a new file in advance on the host (recommended)

It is also very simple to understand. The cause of the problem is that there are no files on both ends and no mount points, so two folders are generated by default. Now that a new file is generated in advance on the host computer, a specific mounting relationship is formed. The operation is as follows:

touch sample.txt #docker-compose.yml同级目录下执行
docker-compose up -d ImageName    #正常启动容器

The rest need not be modified, including Dockerfile and docker-compose.yml, etc.

Second, add files to the container

The second method is to start from the container and generate new files in the container in advance. The idea is the same as above

Add in Dockerflie:

ADD ./sample.tex /code  #在生成code目录后,code在此处是工作目录,可自己修改

The premise is that there is this file in the build environment, which means that this file must also be in the code base

No need to modify the rest, including docker-compose.yml, etc., and then start normally

Summary: The
above two methods have their own advantages and disadvantages. The first one is a little troublesome during deployment, but in fact, you need to create a new file for one deployment, and then you can just copy and paste it directly after deployment. The second method feels more concise when deployed, but it is not recommended to add useless files to the code base. In summary, it is recommended to use the first

Expand

The appeal solution is generated for the file with a specific file name, that is, the solution when the file name is determined.

If the file name is uncertain when the file is generated in our program, for example, as time changes, the appeal method becomes invalid.
There is no good solution to this situation, we can avoid it in the program, put the generated files in a specific folder, and then use the normal mapping relationship.

Guess you like

Origin blog.csdn.net/csdniter/article/details/109214778