简体   繁体   中英

serving Django static files with nginx and gunicorn on kubernetes

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM