在Nginx上部署Create-React-App

前端之家收集整理的这篇文章主要介绍了在Nginx上部署Create-React-App前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

Nginx Conf

  1. server {
  2. listen 80;
  3. server_name app.mydomain.com;
  4. root /srv/app-name;
  5. index index.html index.htm index.js;
  6. access_log /var/log/Nginx/node-app.access.log;
  7. error_log /var/log/Nginx/node-app.error.log;
  8. location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|svg)${
  9. root /srv/app-name/build;
  10. }
  11. location / {
  12. proxy_pass http://127.0.0.1:4000;
  13. proxy_http_version 1.1;
  14. proxy_set_header Upgrade $http_upgrade;
  15. proxy_set_header Connection 'upgrade';
  16. proxy_set_header Access-Control-Allow-Origin *;
  17. proxy_set_header Host $host;
  18. proxy_cache_bypass $http_upgrade;
  19. }
  20. }
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,如下所示:

  1. server {
  2. listen 80;
  3. server_name app.mydomain.com;
  4. root /srv/app-name;
  5. index index.html;
  6. # Other config you desire (logging,etc)...
  7. location / {
  8. try_files $uri /index.html;
  9. }
  10. }

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

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

猜你在找的Nginx相关文章