Django Advanced Tutorial: Executing a Command in Dockerfile Leads to Error
I followed the advanced django tutorial on reusable apps, for which I created a Dockerfile:
FROM python:3.11.11-alpine3.21
# Install packages (acc. to instructions
# https://github.com/gliderlabs/docker-alpine/blob/master/docs/usage.md)
RUN apk --no-cache add curl ca-certificates sqlite git
WORKDIR /app
COPY setup.py .
COPY pyproject.toml .
# Install `uv` acc. to the instructions
# https://docs.astral.sh/uv/guides/integration/docker/#installing-uv
ADD https://astral.sh/uv/0.5.29/install.sh /uv-installer.sh
RUN sh /uv-installer.sh && rm /uv-installer.sh
ENV PATH="/root/.local/bin/:$PATH"
# Install packages with uv into system python
RUN uv pip install --system -e .
# Expose the Django port
EXPOSE 8000
RUN git config --global --add safe.directory /app
Now, I have the following structure:
django-polls-v2/
- dist/
- .gitignore
- django_polls_v2-0.0.1-py3-none-any.whl
- django_polls_v2-0.0.1.tar.gz
- django_polls_v2/
- migrations/
- ...
- static/
- ...
- templates/
- ...
- __init__.py
- admin.py
- ...
- README.rst
- pyproject.toml
- MANIFEST.in
- LICENSE
In order to install my own package, cf. here, the documentation states to execute the following (where I adjusted the filenames to reflect my setting):
python -m pip install --user django-polls-v2/dist/django_polls_v2/0.0.1.tar.gz
Now, when I execute this command inside a running docker container (where I get into the docker container by running
docker run -p 8000:8000 --shm-size 512m --rm -v $(pwd):/app -it django:0.0.1 sh
), the package gets installed.
However, putting the same command into the Dockerfile, I get the error
1.619 WARNING: Requirement 'django-polls-v2/dist/django_polls_v2-0.0.1.tar.gz' looks like a filename, but the file does not exist
1.670 Processing ./django-polls-v2/dist/django_polls_v2-0.0.1.tar.gz
1.671 ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/app/django-polls-v2/dist/django_polls_v2-0.0.1.tar.gz'
However, since the path is correct, I am baffled as to why the error occurs. I already tried to create a non-root user before executing the command, yet to no avail. Any advice?
When you run your container, you map your current working directory into the container using the volume mapping -v $(pwd):/app
. That's why you're able to install the package in that scenario.
When you try to install it during the build process in your Dockerfile, you don't have such a mapping and you don't COPY the file into the image. So the install process can't find it.
A simple way to get it into the image is to replace
COPY setup.py .
COPY pyproject.toml .
with
COPY . .
That will copy your entire directory structure into the image and your tar file will be available.