加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

在Nginx上部署Create-React-App

发布时间:2020-12-13 21:21:56 所属栏目:Nginx 来源:网络整理
导读:我正在尝试使用Ubuntu 14.04和Nginx在Digital Ocean Droplet上部署我的create-react-app SPA.根据静态服务器deployment instructions,当我运行serve -s build -p 4000时,我可以使它工作,但是一旦我关闭终端,应用程序就会关闭.我不清楚create-react-app repo

我正在尝试使用Ubuntu 14.04和Nginx在Digital Ocean Droplet上部署我的create-react-app SPA.根据静态服务器deployment instructions,当我运行serve -s build -p 4000时,我可以使它工作,但是一旦我关闭终端,应用程序就会关闭.我不清楚create-react-app repo自述文件如何让它永远运行,类似于forever之类的东西.

如果没有运行服务,我会收到Nginx的502 Bad Gateway错误.

Nginx Conf

server {
  listen 80;
  server_name app.mydomain.com;
  root /srv/app-name;
  index index.html index.htm index.js;
  access_log /var/log/nginx/node-app.access.log;
  error_log /var/log/nginx/node-app.error.log;
  location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|svg)${
    root   /srv/app-name/build;
  }
  location / {
    proxy_pass http://127.0.0.1:4000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Access-Control-Allow-Origin *;
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}
React(和Create React App)的主要好处之一是您不需要运行Node服务器(或使用Nginx代理它)的开销;您可以直接提供静态文件.

从您链接到的Deployment documentation,Create React App描述了要做的事情:

npm run build creates a build directory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is served index.html,and requests to static paths like /static/js/main. are served with the contents of the /static/js/main. file.

在您的情况下,运行npm run build来创建build /目录,然后在Nginx可以访问它们的位置使文件可用.您的构建可能最适合您的本地计算机,然后将文件安全地复制(SCP,SFTP等)到您的服务器.您可以在服务器上运行npm run build,但如果这样做,抵制直接服务build /目录的诱惑,因为下次运行构建时,客户端可能会收到一组不一致的资源.

无论你选择哪一个,一旦你的构建/目录在你的服务器上,然后检查权限以确保Nginx可以读取文件并配置你的nginx.conf,如下所示:

server {
  listen 80;
  server_name app.mydomain.com;
  root /srv/app-name;
  index index.html;
  # Other config you desire (logging,etc)...
  location / {
    try_files $uri /index.html;
  }
}

此配置基于您的文件位于/ srv / app-name中.简而言之,try_files指令首先尝试加载CSS / JS / images等,并为所有其他URI加载构建中的index.html文件,显示您的应用程序.

需要注意的是,您应该使用HTTPS / SSL进行部署而不是端口80上的不安全HTTP.Certbot为Nginx提供自动HTTPS,并提供免费的Let’s加密证书,如果获得证书的成本或过程会阻止您.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读