将几个与 Docker 相关的文件放在项目根目录中是相当常见的,这可能会为您省去一些麻烦;我建议将其作为首选。
如果您确实想将其全部保存在子目录中,那么这是可能的。当你跑步时docker-compose
, 你可以指定配置文件的位置 https://docs.docker.com/compose/reference/overview/#specifying-a-path-to-a-single-compose-file。它将认为所有路径都是相对于该文件的目录的。
# Either:
docker-compose -f .devcontainer/docker-compose.yml up
cd .devcontainer && docker-compose up
当您构建映像时,构建会读取上下文目录, and COPY
语句总是相对于该目录进行解释。对于您的设置,您需要将上下文目录置于源代码树的顶部,然后在子目录中指定备用 Dockerfile。
services:
web:
build:
context: ..
dockerfile: .dockerenv/Dockerfile
大多数情况下,Dockerfile 本身没问题,但如果入口点脚本位于子目录中,则COPY
命令也需要反映这一点。由于您要复制整个源目录,因此您还可以将图像内的内容重新排列为您想要的布局。
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . ./
# Either:
COPY .dockerenv/entrypoint.sh ./
# Or:
RUN mv .dockerenv/entrypoint.sh .
# Or:
CMD ["./dockerenv/entrypoint.sh"]
我不推荐您拥有的卷结构,但如果您想保留它,您还需要将绑定挂载的源路径更改为父目录。 (特别注意,在前面的 Dockerfile 片段中,有几个选项涉及在映像内移动文件,并且绑定挂载将隐藏该更改。)
services:
web:
volumes:
# Ignore the application built into the container, and use
# whatever's checked out on the host system instead.
- ..:/home/app/microservice
# Further ignore the static assets on the host system and
# use the content in a named volume instead.
- static_volume:/home/app/microservice/static