容器卷未安装到本地路径

Container volume not mounting to local path

Python代码:

with open("/var/lib/TestingVolume.txt", "r") as outFile:
    data = outFile.read()
with open("/var/lib/TestingVolume.txt", "w") as outFile:
    outFile.write("Hi, Hello")

Docker 文件

# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.8-slim
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY . /app
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app /var
USER appuser
# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["python", "WriteData.py"]

docker-compose.yml

version: '3.4'
services:
    newfoldercopy:
        image: newfoldercopy
        build:
          context: .
          dockerfile: ./Dockerfile
        volumes:
          - D:/PythonService:/var/lib/:cached
          - ~:/host-home-folder:cached
          - ./data-subfolder:/data:cached

我正在使用 VS 代码。将所有 docker 文件添加到我的工作区。尝试将本地路径挂载到容器卷。上面的代码没有写入,因为容器正在将数据写入容器虚拟文件系统。 https://code.visualstudio.com/remote/advancedcontainers/add-local-file-mount 文档说我们必须缓存。还是不行。

您挂载到 /var/lib/data 但写入 /var/lib 因此您写入的路径不在或低于挂载路径。

修复它的最简单方法可能是更改您的代码,以便您像这样写入 /var/lib/data

with open("/var/lib/data/TestingVolume.txt", "r") as outFile:
    data = outFile.read()
with open("/var/lib/data/TestingVolume.txt", "w") as outFile:
    outFile.write("Hi, Hello")