pythondockerdocker-compose

Python cannot use bind mounted files in Docker


There is my simplified code that causes problems

env_path = "resources/.env"
if os.path.exists(env_path):
    load_dotenv(env_path)
else:
    raise ResourcesMissing('.env missing')

tg_token_env = "resources/tg_token.env"
if os.path.exists(tg_token_env):
    load_dotenv(tg_token_env)
else:
    raise ResourcesMissing('tg_token.env missing')

This code raises exception in docker but works fine on my win pc

docker-compose.yml

services:
  bot:
    build: .
    volumes:
      - ./media:/app/media:ro
      - ./resources:/app/resources:rw

Dockerfile

FROM python:3.13.5-slim
WORKDIR /usr/src/app
ENV CONTAINER=docker

RUN mkdir -p /app/media
RUN mkdir -p /app/resources

RUN apt-get update
RUN pip install --upgrade pip
COPY . .

[Installing dependencies]

CMD ["python", "bot.py"]

also i have .dockerignore file

media/*
resources/*

I checked the Files tab on the Docker desktop and the container has mounted the files, but Python can't read them. files tab

Im tried different formations of docker-compose.yml. Tried to pack .env file in image and it works but i need it in mount bind. Tried to define env_file in docker-compose.yml. I tried many things but always getting exception


Solution

  • The problem is that, due to the WORKDIR setting in your Dockerfile, your code lives in, and runs in, the directory /usr/src/app and is therefore expecting to find the resources in /usr/src/app/resources. However, your Dockerfile and docker-compose.yml file are expecting the resources and media to be mounted in /app.

    You either need to move the mounts in docker-compose.yml so that they live under /usr/src/app; move the WORKDIR directory (and therefore the application installation) in your Dockerfile so that it lives under /app; or do more extensive modifications to the Dockerfile and your python script so that the script and its packages can live in /usr/src/app while expecting resources and media to live in /app.