在kubernetes上使用nginx和gunicorn提供Django静态文件

时间:2018-09-08 00:15:42

标签: django docker nginx kubernetes

我有Docker,nginx和gunicorn的Django应用程序。

我正在尝试使用nginx来提供静态文件,但是却收到404。

这是我的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清单文件: Nginx和应用程序是同一部署中的两个单独的容器。

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'),)

nginx的Dockerfile:

FROM nginx:latest

ADD app/api/static /api/static

ADD config/nginx /etc/nginx

WORKDIR /api

我在nginx容器中签入,所有静态文件都在/ api目录中。

1 个答案:

答案 0 :(得分:0)

您需要创建一个卷并与nginx和您的django后端共享,然后在该卷中收集静电!但有一个问题 。您的集群需要支持`accessModes:

  • ReadWriteMany`用于pvc存储!如果您无权访问tjis,则可以创建一个具有两个容器的应用程序!您的django后端和nginx!那么您可以在它们之间共享音量!