首页 > 解决方案 > 使用 nginx 部署 django 并在云上做出反应

问题描述

我有一个 digitalocean 服务器,我已经使用 gunicorn 和 nginx 部署了我的 Django 后端服务器。

如何在同一台服务器上部署 React 应用程序?

标签: reactjsdjangonginxclouddigital-ocean

解决方案


  • 您可以构建 React 应用程序并使用 Nginx 提供其静态文件
  • 您可以使用 docker-compose 来管理 Nginx 和 Django。更重要的是,您可以在 docker build 期间构建 React 静态文件。

这是我的文章: Docker-Compose for Django and React with Nginx reverse-proxy 和 Let's encrypt certificate

在我的 Nginx 配置下面:

server {
    listen 80;
    server_name _;
    server_tokens off;
    client_max_body_size 20M;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location /api {
        try_files $uri @proxy_api;
    }
    location /admin {
        try_files $uri @proxy_api;
    }

    location @proxy_api {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass   http://backend:8000;
    }

    location /django_static/ {
        autoindex on;
        alias /app/backend/server/django_static/;
    }
}

Nginx 码头文件:

# The first stage
# Build React static files
FROM node:13.12.0-alpine as build

WORKDIR /app/frontend
COPY ./frontend/package.json ./
COPY ./frontend/package-lock.json ./
RUN npm ci --silent
COPY ./frontend/ ./
RUN npm run build

# The second stage
# Copy React static files and start nginx
FROM nginx:stable-alpine
COPY --from=build /app/frontend/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]

推荐阅读