I’m running a Django application in a Docker container, and I’m having trouble serving static files in production. Everything works fine locally, but when I deploy to production, the static files don’t load, and I get 404 errors.
Here are the relevant parts of my setup:
Django settings.py
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/vol/web/static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build', 'static')]
After running collectstatic
, the volume /vol/web/static
is correctly populated. However, the browser shows 404 errors for the static files, e.g.,
GET https://www.aloconcursos.com/static/js/main.db771bdd.js [HTTP/2 404 161ms]
GET https://www.aloconcursos.com/static/css/main.4b763604.css [HTTP/2 404 160ms]
Loading failed for the <script> with source “https://www.aloconcursos.com/static/js/main.db771bdd.js”.
These files exist in the build/static
directory, but I thought the browser should use the static files collected into /vol/web/static
.
Nginx Configuration:
server {
listen ${LISTEN_PORT};
location /static {
alias /vol/static;
}
location / {
uwsgi_pass ${APP_HOST}:${APP_PORT};
include /etc/nginx/uwsgi_params;
client_max_body_size 10M;
}
}
Dockerfile:
FROM python:3.9-alpine
ENV PYTHONUNBUFFERED 1
ENV PATH="/scripts:${PATH}"
RUN pip install --upgrade "pip<24.1"
COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache postgresql-client jpeg-dev
&& apk add --update --no-cache --virtual .tmp-build-deps
gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev libffi-dev
&& pip install -r /requirements.txt
&& apk del .tmp-build-deps
RUN mkdir -p /app /vol/web/media /vol/web/static
RUN adduser -D user
RUN chown -R user:user /vol /app
COPY ./app /app
COPY ./scripts /scripts
COPY ./requirements.txt /requirements.txt
RUN chmod -R 755 /vol/web /app /scripts
&& chmod +x /scripts/*
USER user
WORKDIR /app
VOLUME /vol/web
CMD ["entrypoint.sh"]
I suspect there might be an issue with file permissions, but after I change the permission the errors continue. Any insights on what might be going wrong or how to debug this further?
Any help would be greatly appreciated!