Docker build using volumes at build time

此生再无相见时 提交于 2020-12-31 04:32:13

问题


Is there a way to use external volumes during the docker image build ?

I have a situation where I would like to use a configuration inside a external volume during the docker image build time. Is that possible?


回答1:


If by 'docker image build' you mean running a single 'docker build ...' command: no, there is no way to do that (at least, not in the most recent documentation that I have read). However, nothing prevents you from performing the step that needs the external volume using direct docker commands and then commit the container and tag it just as 'docker build' would. Assuming this is the last step in your build, put all other commands (that don't need the volume) into a Dockerfile and then do this:

tmp_img=`docker build .`
tmp_container=`docker run -v $my_ext_volume:$my_mount_path --entrypoint=(your volume-dependent build command here) $tmp_img`
docker commit $tmp_container my_repo/image_tag:latest
docker rm "$tmp_container"

This does the same as having a RUN command in the Dockerfile, but with the added volume mount. The commit command in the example also tags the image.

It is a bit more complex if you need to have other Dockerfile commands after the volume-dependent one, but in most cases you can combine run commands and re-arrange your install in a way that leaves the manual run-with-volume command last, to keep things simple.




回答2:


You can copy the file into the docker image (ADD) and rm as one of the last steps




回答3:


You can use ADD combined with ARG (build time parameters) to access files or directories during the build without having to hardcode their location.

ARG MAVEN_SETTINGS=settings.xml
ADD $MAVEN_SETTINGS ./

And now you can change the file location during the build with:

docker build --build-arg MAVEN_SETTINGS=someotherfile.xml



回答4:


podman is an alternative to Docker that has an api that is the same BUT also supports mounting volumes at buildtime.

I use this to load data into testdatabases without having to copy the data into the image first.




回答5:


We are not restricted to Docker to build OCI images.

With buildah it's possible to mount volumes from the host that won't be persisted in the final image. Useful for configuration and secrets.

buildah bud --volume /home/test:/myvol:ro -t imageName .



来源:https://stackoverflow.com/questions/51086724/docker-build-using-volumes-at-build-time

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