by Andrea Stringham

通过安德里亚·斯特拉姆(Andrea Stringham)

我建了这个-现在呢? 如何在DigitalOcean Droplet上部署React App。 (I Built This - Now What? How to deploy a React App on a DigitalOcean Droplet.)

Most aspiring developers have uploaded static HTML sites before. The process isn’t too daunting, as you’re essentially just moving files from one computer to another, and then BAM! Website.

大多数有抱负的开发人员以前都上传过静态HTML网站。 这个过程并不十分艰巨,因为实际上您只是将文件从一台计算机移至另一台计算机,然后移至BAM! 网站。

But those who have tackled learning React often pour hundreds or even thousands of hours into learning about components, props, and state, only to be left with the question “How do I host this?” Fear not, fellow developer. Deploying your latest masterpiece is a little more in-depth, but not overly difficult. Here’s how:

但是那些致力于学习React的人通常会花费数百甚至数千小时来学习有关组件,道具和状态的知识,而只剩下一个问题:“我该如何托管?” 别担心,开发人员。 部署您的最新杰作需要更深入一些,但并不太困难。 这是如何做:

准备生产 (Preparing For Production)

There are a few things you’ll want to do to get your app ready for deployment.

您需要做一些事情来使您的应用程序为部署做好准备。

关闭服务人员 (Turn off service workers)

If you’ve used something like create-react-app to bootstrap your project, you’ll want to turn off the built-in service worker if you haven’t specifically integrated it to work with your app. While usually harmless, it can cause some issues, so it’s best to just get rid of it up front. Find these lines in your src/index.js file and delete them:registerServiceWorker(); import registerServiceWorker from ‘register-service-worker’

如果您使用过诸如create-react-app之类的程序来引导您的项目,则如果您没有专门将其集成到应用程序中,则需要关闭内置服务工作器。 尽管通常无害,但它可能会引起一些问题,因此最好先将其消除。 在src/index.js文件中找到以下行并将其删除: registerServiceWorker(); import registerServiceWorker from 'register-service-worker'

准备您的服务器 (Get your server ready)

To get the most bang for your buck, a production build will minify the code and remove extra white-space and comments so that it’s as fast to download as possible. It creates a new directory called /build, and we need to make sure we’re telling Express to use it. On your server page, add this line: app.use( express.static( `${__dirname}/../build` ) );

为了最大程度地发挥作用,生产版本将减少代码并删除多余的空格和注释,以便尽可能快地下载。 它创建了一个名为/build的新目录,我们需要确保告诉Express使用它。 在服务器页面上,添加以下行: app.use( express.static( `${__dirname}/../build` ) );

Next, you’ll need to make sure your routes know how to get to your index.html file. To do this, we need to create an endpoint and place it below all other endpoints in your server file. It should look like this:

接下来,您需要确保您的路线知道如何到达index.html文件。 为此,我们需要创建一个端点并将其放置在服务器文件中所有其他端点的下方。 它看起来应该像这样:

const path = require('path')app.get('*', (req, res)=>{  res.sendFile(path.join(__dirname, '../build/index.html'));})

创建生产版本 (Create the production build)

Now that Express knows to use the /build directory, it’s time to create it. Open up your terminal, make sure you’re in your project directory, and use the command npm run build

现在,Express知道可以使用/build目录了,现在该创建它了。 打开终端,确保您位于项目目录中,并使用命令npm run build

保守秘密 (Keep your secrets safe)

If you’re using API keys or a database connection string, hopefully you’ve already hidden them in a .env file. All the configuration that is different between deployed and local should go into this file as well. Tags cannot be proxied, so we have to hard code in the backend address when using the React dev server, but we want to use relative paths in production. Your resulting .env file might look something like this:

如果您使用的是API密钥或数据库连接字符串,则希望您已经将它们隐藏在.env文件中。 部署和本地配置之间所有不同的配置也应放入此文件中。 标签不能被代理,因此在使用React开发服务器时,我们必须在后端地址中进行硬编码,但是我们想在生产中使用相对路径。 您生成的.env文件可能看起来像这样:

REACT_APP_LOGIN="http://localhost:3030/api/auth/login"REACT_APP_LOGOUT="http://localhost:3030/api/auth/logout"DOMAIN="user4234.auth0.com"ID="46NxlCzM0XDE7T2upOn2jlgvoS"SECRET="0xbTbFK2y3DIMp2TdOgK1MKQ2vH2WRg2rv6jVrMhSX0T39e5_Kd4lmsFz"SUCCESS_REDIRECT="http://localhost:3030/"FAILURE_REDIRECT="http://localhost:3030/api/auth/login"
AWS_ACCESS_KEY_ID=AKSFDI4KL343K55L3AWS_SECRET_ACCESS_KEY=EkjfDzVrG1cw6QFDK4kjKFUa2yEDmPOVzN553kAANcy
CONNECTION_STRING="postgres://vuigx:k8Io13cePdUorndJAB2ijk_u0r4@stampy.db.elephantsql.com:5432/vuigx"NODE_ENV=development

推送您的代码 (Push your code)

Test out your app locally by going to http://localhost:3030 and replacing 3030 with your server port to make sure everything still runs smoothly. Remember to start your local server with node or nodemon so it’s up and running when you check it. Once everything looks good, we can push it to Github (or Bit Bucket, etc).

转到http://localhost:3030然后用服务器端口替换3030,以确保一切仍然正常运行,以在本地测试您的应用。 请记住要使用node或nodemon启动本地服务器,以便在检查时启动并运行它。 一旦一切看起来不错,我们就可以将其推送到Github(或Bit Bucket等)。

IMPORTANT! Before you do so, double check that your .gitignore file contains .env and /build so you’re not publishing sensitive information or needless files.

重要! 在执行此操作之前,请仔细检查.gitignore文件是否包含.env/build.env您不会发布敏感信息或不必要的文件。

设置DigitalOcean (Setting Up DigitalOcean)

DigitalOcean is a leading hosting platform, and makes it relatively easy and cost-effective to deploy React sites. They utilize Droplets, which is the term they use for their servers. Before we create our Droplet, we still have a little work to do.

DigitalOcean是领先的托管平台,使部署React站点相对容易且具有成本效益。 他们利用Droplet,这是他们用于服务器的术语。 在创建Droplet之前,我们还有一些工作要做。

创建SSH密钥 (Creating SSH Keys)

Servers are computers that have public IP addresses. Because of this, we need a way to tell the server who we are, so that we can do things we wouldn’t want anyone else doing, like making changes to our files. Your everyday password won’t be secure enough, and a password long and complex enough to protect your Droplet would be nearly impossible to remember. Instead, we’ll use an SSH key.

服务器是具有公共IP地址的计算机。 因此,我们需要一种方法来告知服务器我们是谁,以便我们可以执行不希望其他人执行的操作,例如更改文件。 您的日常密码不够安全,并且足够长且复杂的密码来保护您的Droplet将几乎不记得。 相反,我们将使用SSH密钥。

To create your SSH key, enter this command in your terminal: ssh-keygen -t rsa

要创建SSH密钥,请在终端中输入以下命令: ssh-keygen -t rsa

This starts the process of SSH key generation. First, you’ll be asked to specify where to save the new key. Unless you already have a key you need to keep, you can keep the default location and simply press enter to continue.

这将启动SSH密钥生成过程。 首先,系统会要求您指定新密钥的保存位置。 除非您已经有需要保留的密钥,否则可以保留默认位置,只需按Enter即可继续。

As an added layer of security in case someone gets ahold of your computer, you’ll have to enter a password to secure your key. Your terminal will not show your keystrokes as you type this password, but it is keeping track of it. Once you hit enter, you’ll have to type it in once more to confirm. If successful, you should now see something like this:

如果有人使用您的计算机,这是增加的安全保护层,您必须输入密码来保护密钥。 当您键入此密码时,终端将不会显示您的按键,但它会一直在跟踪它。 按下Enter键后,您必须再次输入一次以确认。 如果成功,您现在应该看到类似以下内容:

Generating public/private rsa key pair.Enter file in which to save the key (/Users/username/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in demo_rsa.Your public key has been saved in demo_rsa.pub.The key fingerprint is:cc:28:30:44:01:41:98:cf:ae:b6:65:2a:f2:32:57:b5 user@user.localThe key's randomart image is:+--[ RSA 2048]----+|=*+.             ||o.               || oo              ||  oo  .+         || .  ....S        ||  . ..E          || . +             ||*.=              ||+Bo              |+-----------------+

发生了什么? (What happened?)

Two files have been created on your computer — id_rsa and id_rsa.pub. The id_rsa file is your private key and is used to verify your signature when you use the id_rsa.pub file, or public key. We need to give our public key to DigitalOcean. To get it, enter cat ~/.ssh/id_rsa.pub. You should now be looking at a long string of characters, which is the contents of your id_rsa.pub file. It looks something like this:

您的计算机上已经创建了两个文件id_rsaid_rsa.pubid_rsa文件是您的私钥,并且在您使用id_rsa.pub文件或公钥时用于验证签名。 我们需要将公开密钥提供给DigitalOcean。 要获取它,请输入cat ~/.ssh/id_rsa.pub 。 现在,您应该查看一长串字符,这是id_rsa.pub文件的内容。 看起来像这样:

ssh-rsaAABC3NzaC1yc2EAAAADAQABAAABAQDR5ehyadT9unUcxftJOitl5yOXgSi2Wj/s6ZBudUS5Cex56LrndfP5Uxb8+Qpx1D7gYNFacTIcrNDFjdmsjdDEIcz0WTV+mvMRU1G9kKQC01YeMDlwYCopuENaas5+cZ7DP/qiqqTt5QDuxFgJRTNEDGEebjyr9wYk+mveV/acBjgaUCI4sahij98BAGQPvNS1xvZcLlhYssJSZrSoRyWOHZ/hXkLtq9CvTaqkpaIeqvvmNxQNtzKu7ZwaYWLydEKCKTAe4ndObEfXexQHOOKwwDSyesjaNc6modkZZC+anGLlfwml4IUwGv10nogVg9DTNQQLSPVmnEN3Z User@Computer.local

Now that’s a password! Copy the string manually, or use the command pbcopy < ~/.ssh/id_rsa.pub to have the terminal copy it for you.

现在这是一个密码! 手动复制字符串,或使用命令pbcopy < ~/.ssh/id_rsa. pub让终端为您复制它。

将SSH密钥添加到DigitalOcean (Adding your SSH Key to DigitalOcean)

Login to your DigitalOcean account or sign up if you haven’t already. Go to your Security Settings and click on Add SSH. Paste in the key you copied and give it a name. You can name it whatever you like, but it’s good idea to reference the computer the key is saved on, especially if you use multiple computers regularly.

登录到您的DigitalOcean帐户或注册(如果尚未注册)。 转到“ 安全设置” ,然后单击“添加SSH”。 粘贴您复制的密钥并为其命名。 您可以随意命名,但是最好参考保存密钥的计算机,尤其是当您定期使用多台计算机时。

创建一个液滴 (Creating a Droplet)

With the key in place, we can finally create our Droplet. To get started, click Create Droplet. You’ll be asked to choose an OS, but for our purposes, the default Ubuntu will work just fine.

有了密钥,我们终于可以创建我们的Droplet。 首先,单击创建液滴。 系统会要求您选择一个操作系统,但是出于我们的目的,默认的Ubuntu可以正常工作。

You’ll need to select which size Droplet you want to use. In many cases, the smallest Droplet will do. However, review the available options and choose the one that will work best for your project.

您需要选择要使用的液滴尺寸。 在许多情况下,最小的Droplet会起作用。 但是,请查看可用选项,然后选择最适合您的项目的选项。

Next, select a data center for your Droplet. Choose a location central to your expected visitor base. New features are rolled out by DigitalOcean in different data centers at different times, but unless you know you want to use a special feature that’s only available in specific locations, this won’t matter.

接下来,为您的Droplet选择一个数据中心。 选择您期望的访问者中心的中心位置。 DigitalOcean会在不同的时间在不同的数据中心推出新功能,但是除非您知道要使用仅在特定位置可用的特殊功能,否则这没有关系。

If you want to add additional services to your Droplet such as backups or private networking, you have that option here. Be aware, there is an associated cost for these services.

如果要向Droplet添加其他服务(例如备份或专用网络),请在此处使用该选项。 请注意,这些服务会产生相关费用。

Finally, make sure your SSH key is selected and give your Droplet a name. It is possible to host multiple projects on a single Droplet, so you may not want to give it a project-specific name. Submit your settings by clicking the Create button at the bottom of the page.

最后,确保选择了SSH密钥,并为Droplet命名。 可以在单个Droplet上托管多个项目,因此您可能不想为其指定特定于项目的名称。 通过单击页面底部的“创建”按钮提交设置。

连接到您的Droplet (Connecting to your Droplet)

With our Droplet created, we can now connect to it via SSH. Copy the IP address for your Droplet and go back to your terminal. Enter ssh followed by root@youripaddress, where youripaddress is the IP address for your Droplet. It should look something like this: ssh root@123.45.67.8. This tells your computer that you want to connect to your IP address as the root user. Alternatively, you can set up user accounts if you don’t want to login as root, but it’s not necessary.

创建了Droplet之后,我们现在可以通过SSH连接到它。 复制Droplet的IP地址,然后返回到终端。 输入ssh,然后输入root @ youripaddress,其中youripaddress是Droplet的IP地址。 它应该看起来像这样: ssh root@123.45.67.8 。 这告诉您的计算机您要以root用户身份连接到IP地址。 另外,如果您不想以root 用户身份登录,则可以设置用户帐户 ,但这不是必需的。

安装节点 (Installing Node)

To run React, we’ll need an updated version of Node. First we want to run apt-get update && apt-get dist-upgrade to update the Linux software list. Next, enter apt-get install nodejs -y, apt-get install npm -y, and npm i -g n to install Nodejs and npm.

要运行React,我们需要Node的更新版本。 首先,我们要运行apt-get update && apt-get dist-upgrade来更新Linux软件列表。 接下来,输入apt-get install nodejs -yapt-get install npm -ynpm i -gn以安装Nodejs和npm。

Your React app dependencies might require a specific version of Node, so check the version that your project is using by running node -v in your projects directory. You’ll probably want to do this in a different terminal tab so you don’t have to log in through SSH again.

您的React应用程序依赖项可能需要特定版本的Node,因此请通过在项目目录中运行node -v来检查项目所使用的版本。 您可能需要在其他终端选项卡中执行此操作,因此不必再次通过SSH登录。

Once you know what version you need, go back to your SSH connection and run n 6.11.2, replacing 6.11.2 with your specific version number. This ensures your Droplet’s version of Node matches your project and minimizes potential issues.

一旦知道所需的版本,请返回SSH连接并运行n 6.11.2 ,将6.11.2替换为您的特定版本号。 这可确保您的Droplet的Node版本与您的项目匹配,并最大程度地减少潜在问题。

将您的应用安装到Droplet (Install your app to the Droplet)

All the groundwork has been laid, and it’s finally time to install our React app! While still connected through SSH, make sure you’re in your home directory. You can enter cd ~ to take you there if you’re not sure.

所有的基础工作都已经奠定了,现在是时候安装我们的React应用程序了! 仍通过SSH连接时,请确保您位于主目录中。 如果不确定,可以输入cd ~带您到那里。

To get the files to your Droplet, you’re going to clone them from your Github repo. Grab the HTTP clone link from Github and in your terminal enter git clone https://github.com/username/my-react-project.git. Just like with your local project, cd into your project folder using cd my-react-project and then run npm install.

要将文件发送到Droplet,您需要从Github存储库中克隆它们。 从Github中获取HTTP克隆链接,然后在您的终端中输入git clone https://github.com/username/my-react-project.git 。 就像本地项目一样,使用cd my-react-project cd放入项目文件夹,然后运行npm install

不要忽略您忽略的文件 (Don’t ignore your ignored files)

Remember that we told Git to ignore the .env file, so it won’t be included in the code we just pulled down. We need to add it manually now. touch .env will create an empty .env file that we can then open in the nano editor using nano .env. Copy the contents of your local .env file and paste them into the nano editor.

请记住,我们告诉Git忽略.env文件,因此它不会包含在我们刚刚下拉的代码中。 我们现在需要手动添加它。 touch .env将创建一个空的.env文件,然后可以使用nano .env在nano编辑器中打开该nano .env 。 复制本地.env文件的内容,然后将其粘贴到nano编辑器中。

We also told Git to ignore the build directory. That’s because we were just testing the production build, but now we’re going to build it again on our Droplet. Use npm run build to run this process again. If you get an error, check to make sure you have all of your dependencies listed in your package.json file. If there are any missing, npm install those packages.

我们还告诉Git忽略构建目录。 那是因为我们只是在测试生产版本,但是现在我们要在Droplet上再次构建它。 使用npm run build再次运行此过程。 如果遇到错误,请检查以确保在package.json文件中列出了所有依赖项。 如果缺少任何内容,请npm安装这些软件包。

开始吧! (Start it up!)

Run your server with node server/index.js (or whatever your server file is named) to make sure everything is working. If it throws an error, check again for any missing dependencies that might not have been caught in the build process. If everything starts up, you should now be able to go to ipaddress:serverport to see your site: 123.45.67.8:3232. If your server is running on port 80, this is a default port and you can just use the IP address without specifying a port number: 123.45.67.8

使用node server/index.js (或任何命名的服务器文件)运行服务器,以确保一切正常。 如果抛出错误,请再次检查是否可能在构建过程中未捕获到任何缺少的依赖项。 如果一切开始,您现在应该可以访问ipaddress:serverport来查看您的站点: 123.45.67.8:3232 : 123.45.67.8:3232 。 如果您的服务器在端口80上运行,则这是默认端口,您可以使用IP地址而不指定端口号: 123.45.67.8

You now have a space on the internet to call your own! If you have purchased a domain name you’d like to use in place of the IP address, you can follow DigitalOcean’s instructions on how to set this up.

您现在可以在互联网上打电话给自己的空间! 如果您购买了想要代替IP地址使用的域名,则可以按照DigitalOcean的说明进行设置。

保持运行 (Keep it running)

Your site is live, but once you close the terminal, your server will stop. This is a problem, so we’ll want to install some more software that will tell the server not to stop once the connection is terminated. There are some options for this, but let’s use Program Manager 2 for the sake of this article.

您的站点已启用,但是一旦关闭终端,服务器将停止。 这是一个问题,因此我们将要安装更多软件,这些软件将告诉服务器一旦连接终止就不要停止。 可以使用一些选项,但是出于本文的目的,让我们使用Program Manager 2。

Kill your server if you haven’t already and run npm install -g pm2. Once installed, we can tell it to run our server using pm2 start server/index.js

如果尚未杀死服务器,请运行npm install -g pm2 。 安装完成后,我们可以告诉它使用pm2 start server/index.js运行服务器。

更新代码 (Updating your code)

At some point, you’ll probably want to update your project, but luckily uploading changes is quick and easy. Once you push your code to Github, ssh into your Droplet and cd into your project directory. Because we cloned from Github initially, we don’t need to provide any links this time. You can pull down the new code simply by running git pull.

在某个时候,您可能需要更新项目,但是幸运的是,上传更改是快速,容易的。 将代码推送到Github后,将ssh放入Droplet,然后将cd放入项目目录。 因为我们最初是从Github克隆的,所以这次我们不需要提供任何链接。 您可以简单地通过运行git pull来提取新代码。

To incorporate frontend changes, you will need to run the build process again with npm run build. If you’ve made changes to the server file, restart PM2 by running pm2 restart all. That’s it! Your updates should be live now.

要合并前端更改,您将需要使用npm run build再次运行构建过程。 如果对服务器文件进行了更改,请通过运行pm2 restart all重启PM2。 而已! 您的更新现在应该已经生效。

翻译自: https://www.freecodecamp.org/news/i-built-this-now-what-how-to-deploy-a-react-app-on-a-digitalocean-droplet-662de0fe3f48/

我建了这个-现在呢? 如何在DigitalOcean Droplet上部署React App。相关推荐

  1. linux mysql搭建禅道详细教程_如何在Linux服务器上部署禅道

    目前较受欢迎的开源项目管理软件:禅道. 这是一款国产的优秀开源项目管理软件,基于敏捷项目管理理念开发而成,操作简洁,能够很好地满足目前团队中的产品.开发.测试等人员的使用. 下面详细介绍如何在Linu ...

  2. 如何在Linux系统上部署接口测试环境

    作为一名软件测试人员,部署测试环境是我们日常工作的一部分,今天就简单整理下接口测试环境部署的步骤,希望能够帮助到大家. 今天为大家整理的接口测试环境部署涉及到Tomcat,JDK和数据库.目前能够提供 ...

  3. aws fargate_我如何在AWS Fargate上部署#100DaysOfCloud Twitter Bot

    aws fargate After passing my last certification, I asked myself how much time I spent studying cloud ...

  4. linux部署jar项目报错_如何在Linux服务器上部署jar包

    启动程序方法 1.上传jar包到linux服务器下 2.启动jar包 ​前台模式 java –jar XXXX.jar(注意这个命令启动时,断开服务连接后,服务就关闭了) ​后台模式 nohup ja ...

  5. exi 虚拟服务器,图文教程:如何在ESXi主机上部署VMware Tools 10

    2015年9月VMware发布了VMware Tools 10.伴随着这次更新,VMware Tools 可能成为一款单独管理的产品.VMware Tools 10不再包含在ESXi的发布周期内,它拥 ...

  6. linux建立ss服务器,如何在linux服务器上部署ss服务

    满意答案 rqyfo 2017.12.13 采纳率:42%    等级:12 已帮助:19585人 ss是Socket Statistics的缩写.顾名思义,ss命令可以用来获取socket统计信息, ...

  7. 如何在OpenStack Kolla上部署Tungsten Fabric(附14个常见的配置问题)

    首先,使用contil-kolla-ansible-deployer容器在OpenStack Kolla上部署Tungsten Fabric(注:原文为Contrail,本文以功能一致的Tungste ...

  8. vscode重置应用程序_如何在Windows 10上重置应用程序的数据

    vscode重置应用程序 With Windows 10's Anniversary Update, you can now reset an app's data without actually ...

  9. 如何在 Amazon EKS 中部署 SR-IOV 设备插件

    前言 随着云技术和容器的发展,越来越多的基于容器集群的通信负载开始在公有云上运行,通信负载对网络性能要求极高,因此广泛使用 SR-IOV 技术来提升网络的吞吐量和减少抖动,同时降低应用的 CPU 开销 ...

最新文章

  1. Elasticsearch 如何做到快速检索 - 倒排索引的秘密
  2. python 测试linux dev文件,Linux测试开发人员要掌握的Linux命令有哪些?
  3. MySQL FEDERATED引擎使用示例, 类似Oracle DBLINK
  4. 为什么在定义hashcode时要使用31这个数呢
  5. FineReport连接mysql8.0.16
  6. 模拟银行自助终端系统
  7. DataGridView控件用法二:常用属性
  8. 计算机网络(五)——组建客户机/服务器网络
  9. 嵌入式学习流程(参考一)
  10. 【BZOJ-3573】米特运输 树形DP
  11. hadoop put命令的格式_【Hadoop篇】--Hadoop常用命令总结
  12. Avalondock 第四步 边缘停靠
  13. 【Android】Xposed 框架解析
  14. Spss-多元回归案例实操
  15. 「ZigBee模块」基础实验(4)定时器T1的简单应用
  16. SAP与 WebService接口的配置与调用
  17. 得洲奥斯汀研究生计算机专业排名,德克萨斯大学奥斯汀分校世界排名及专业排名汇总(QS世界大学排名版)...
  18. 人人网,给我个“上”你的理由吧?
  19. 离谱,还有这种自暴自弃的翻译?
  20. CentOS6.4离线安装mysql5.6.22

热门文章

  1. 使用匿名内部类实现方式二线程创建 java 1615474836
  2. 演练 宠物店挑小动物 java 1615136001
  3. 数据结构与算法-索引1909
  4. 记一次ElasticSearch 更改 mapping 字段类型的过程
  5. [转]IT开发工程师的悲哀
  6. flask-sqlalchemy分表解决方案
  7. Linux模拟超级终端minicom(二)
  8. 面试官系统精讲Java源码及大厂真题 - 33 CountDownLatch、Atomic 等其它源码解析
  9. 如何使用Caddy部署Vue项目
  10. linux find命令mtime/atime/ctime +n -n n 全网最正确的总结