The original post: /r/nginx by /u/Defiant-Option-6833 on 2024-10-11 06:36:52.
I'm not sure if this should be in the nginx or Django Reddit, I posted in the django reddit and folks just told me to use whitenoise. My blog is running on Docker. Initially, all images in the static files folder *from the first set of articles I created while coding the blog* were accessible to nginx. However, when I tried adding articles from the admin panel after deployment, the new images returned a 404 error. I tried debugging by checking my code and realized I didn't include a path for the media folder in the settings.py file. After adding that line and rebuilding the container... well, the previously accessible images are returning 404 as well. I think my nginx server might not be configured correctly. *I've entered the container and verified that files are present.*
nginx conf:
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types {
text/html html;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
fontopentype otf;
fonttruetype ttf;
fontwoff woff;
fontwoff2 woff2;
}
server {
listen 80;
server_name www.redacted.com;
location / {
proxy_pass http://web:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static/ {
alias /usr/src/app/staticfiles/;
}
location /media/ {
alias /usr/src/app/media/;
}
}
}
Dockerfile
# Use the official Python image from the Docker Hub
FROM python:3.11
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set the working directory
WORKDIR /app
# Copy the requirements file into the container
COPY requirements.txt /app/
# Install the dependencies
RUN pip install --upgrade pip && pip install -r requirements.txt
# Copy the entire project into the container
COPY . /app/
# Collect static files
RUN python manage.py collectstatic --noinput
EXPOSE 1617
# Run the Gunicorn server
CMD ["gunicorn", "redacted.wsgi:application", "--bind", "0.0.0.0:1617"]
Docker compose yml
version: '3'
services:
web:
build: .
command: gunicorn --workers 3 redacted.wsgi:application
volumes:
- .:/usr/src/app
expose:
- "1617"
environment:
DJANGO_SECRET_KEY: 'redacted'
DJANGO_DEBUG: 'False'
restart: always
nginx:
image: nginx:latest
ports:
- "1617:1617"
- "400:400"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./staticfiles:/usr/src/app/staticfiles
- ./media:/usr/src/app/media
depends_on:
- web
restart: always