Docker-Compose目录配置问题:Python容器构建后找不到manage.py
Looks like your container can’t find manage.py because your project files aren’t being copied into the right directory inside the container, or your working directory isn’t set correctly. Let’s fix this step by step:
1. Fix Your Dockerfile
Since your Dockerfile lives in the python subfolder, you need to reference the django.testsite directory (where manage.py lives) using a relative path. Here’s an updated, functional Dockerfile:
# Use an official Python runtime as the base image FROM python:3.9-slim # Set the default working directory inside the container WORKDIR /app # If you have a requirements.txt, copy it first to leverage Docker's build cache COPY ../django.testsite/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy the entire Django project from your local `django.testsite` folder to the container's /app directory COPY ../django.testsite/ . # Run the Django dev server, binding to 0.0.0.0 so it's accessible outside the container CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"]
2. (Optional) Simplify Paths with docker-compose.yml Adjustment
You can also set the build context to your project root folder in docker-compose.yml, which makes paths in your Dockerfile more intuitive. Update your docker-compose.yml like this:
version: '3' services: web: build: context: . # Sets the build context to your project root (folder_project) dockerfile: ./python/Dockerfile # Points to your Dockerfile in the python subfolder ports: - "5000:5000" redis: image: redis:alpine # Replace with your actual Redis image
Then simplify your Dockerfile to use paths relative to the project root:
FROM python:3.9-slim WORKDIR /app COPY django.testsite/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY django.testsite/ . CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"]
Why This Fixes the Issue
WORKDIR /appsets the default directory where your container runs commands, so when you executepython manage.py, it looks for the file directly in/app.- The
COPYcommands ensure all files from your localdjango.testsitefolder (includingmanage.py) are copied into the container’s/appdirectory. - Binding the server to
0.0.0.0:5000ensures the Django server is accessible from outside the container, matching the port mapping in your docker-compose.yml.
After making these changes, rebuild your image and restart the containers with:
docker-compose down && docker-compose build && docker-compose up
内容的提问来源于stack exchange,提问作者S. Dior

