docker-compose.yml文件中允许使用’./'相对路径

version: '3'
	...
	volumes:
		- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
		- ./mongo-volume:/data/db
	...
  1. 会将当前路径下的init-mongo.js文件挂载到容器中的/docker-entrypoint-initdb.d/init-mongo.js,并且设置为只读方式;
  2. 会将当前路径下的mongo-volume目录挂载到容器中/data/db,如果不存在mongo-volume,则会自动创建该目录

但如果是docker run的方式就不能像上面一样用相对路径了

>>> docker run -d --restart always -p 27017-27019:27017-27019 -e MONGO_INITDB_DATABASE=job -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root -v $PWD/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro -v ./mongo-volume:/data/db --name my-mongo-container mongo
docker: Error response from daemon: create ./init-mongo.js: "./init-mongo.js" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path.
See 'docker run --help'.

需要用到$PWD替代点号’.'

>>> docker run -d --restart always -p 27017-27019:27017-27019 -e MONGO_INITDB_DATABASE=job -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root -v $PWD/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro -v $PWD/mongo-volume:/data/db --name my-mongo-container mongo
3081e25a20fa8b2e95850897b3b32b08da298f73d7e458119fa3f2c85b45f020

参考:
https://stackoverflow.com/a/51312525/7151777
https://github.com/moby/moby/issues/4830#issuecomment-404178438

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐