Reputation: 53
I have Django application with Docker, nginx and gunicorn.
I am trying to use nginx to serve the static files but I am getting 404.
here is my nginx.conf:
events {
worker_connections 1024;
}
http {
upstream backend {
ip_hash;
server backend:8000;
}
server {
location /static {
autoindex on;
alias /api/static;
}
location / {
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_pass http://backend;
}
listen 80;
}
}
kubernetes manifest file: Nginx and app are two separate containers within the same deployment.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: backend
namespace: staging
labels:
group: backend
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: <host name>
http:
paths:
- path: /
backend:
serviceName: backend
servicePort: 8000
---
apiVersion: v1
kind: Service
metadata:
name: backend
namespace: staging
labels:
group: backend
spec:
selector:
app: backend
ports:
- port: 8000
targetPort: 8000
name: backend
- port: 80
targetPort: 80
name: nginx
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: backend
namespace: staging
labels:
group: backend
spec:
replicas: 1
template:
metadata:
labels:
app: backend
group: backend
spec:
containers:
- name: nginx
image: <image>
command: [nginx, -g,'daemon off;']
imagePullPolicy: Always
ports:
- containerPort: 80
- name: backend
image: <image>
command: ["gunicorn", "-b", ":8000", "api.wsgi"]
imagePullPolicy: Always
ports:
- containerPort: 8000
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Dockerfile for nginx:
FROM nginx:latest
ADD app/api/static /api/static
ADD config/nginx /etc/nginx
WORKDIR /api
I checked in the nginx container, all static files are present in the /api directory.
Upvotes: 2
Views: 1921
Reputation: 336
You need to create a volume and share it with nginx and your django backend and then python manage.py collectstatic in that volume. But there is a problem, your cluster needs to support ReadWriteMany
in accessModes
for the pvc storage. If you don't have access to this you can create an application that has two containers, your django backend and nginx. Then you can share volumes between them!
Upvotes: 1