1. Reactapplication构建
in deploymentReactapplication之 before , 需要先for构建, 生成可deployment 静态file.
1.1 构建Reactapplication
usingCreate React Appcreation project, 可以usingnpm run buildcommandsfor构建.
npm run build
构建completion after , 会 in project根Table of Contents生成一个buildfile夹, package含所 has 可deployment 静态file.
1.2 构建configurationoptimization
可以throughmodifypackage.json or creation.envfile来configuration构建选项.
// package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
// ...
}
// .envfile
// 设置produceenvironment API地址
REACT_APP_API_URL=https://api.example.com
// 设置构建输出Table of Contents
BUILD_PATH=./dist
// 启用produceenvironmentsource map
GENERATE_SOURCEMAP=true
2. 静态resourcedeployment
Reactapplication构建completion after , 生成 is 静态file, 可以deployment to 任何静态resourceserver on .
2.1 usingNetlifydeployment
Netlify is a 流行 静态网站托管平台, support自动deployment, CDN加速, HTTPSetc.functions.
deployment步骤:
- loginNetlify官网: https://www.netlify.com/
- 点击"New site from Git"按钮
- 选择你 code仓library (GitHub, GitLab or Bitbucket)
- configuration构建选项:
- build command: npm run build
- Publish directory: build
- 点击"deployment site"按钮, etc.待deploymentcompletion
2.2 usingVerceldeployment
Vercel is 另一个流行 静态网站托管平台, support自动deployment, Serverless Functionsetc.functions.
deployment步骤:
- loginVercel官网: https://vercel.com/
- 点击"New Project"按钮
- 选择你 code仓library
- configuration构建选项 (Vercel会automatically detectCreate React Appproject)
- 点击"deployment"按钮, etc.待deploymentcompletion
2.3 usingGitHub Pagesdeployment
GitHub Pages is GitHubproviding 静态网站托管service, 可以免费using.
deployment步骤:
- installationgh-pages依赖:
npm install --save-dev gh-pages - in package.jsonin添加homepage字段 and deploy脚本:
{ "name": "my-app", "version": "0.1.0", "private": true, "homepage": "https://username.github.io/repo-name", "scripts": { // ... "predeploy": "npm run build", "deploy": "gh-pages -d build" }, // ... } - rundeploycommands:
npm run deploy
2.4 usingNginxdeployment
Nginx is a high performance Webserver, 可以用于deployment静态resource.
deployment步骤:
- installationNginx
- 将构建 after 静态filecopy to Nginx 网站根Table of Contents:
cp -r build/* /var/www/html/ - configurationNginx (可选) :
# /etc/nginx/nginx.conf server { listen 80; server_name example.com; root /var/www/html; index index.html; location / { try_files $uri $uri/ /index.html; } # 启用gzip压缩 gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; # cache静态resource location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires 1y; add_header Cache-Control "public, max-age=31536000"; } } - 重启Nginx:
systemctl restart nginx
3. serverdeployment
除了静态resourcedeployment out , 还可以将Reactapplicationdeployment to Node.jsserver on .
3.1 usingExpressdeployment
Express is a 流行 Node.js Webframework, 可以用于deploymentReactapplication.
deployment步骤:
- creationExpressserver:
// server.js const express = require('express'); const path = require('path'); const app = express(); // 静态resourceservice app.use(express.static(path.join(__dirname, 'build'))); // processing所 has routing, 返回index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); // 启动server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is run on port ${port}`); }); - installation依赖:
npm install express - modifypackage.json, 添加start脚本:
{"scripts": { "start": "node server.js", "build": "react-scripts build" }} - 构建application:
npm run build - 启动server:
npm start
3.2 usingPM2managementprocess
PM2 is a Node.jsprocessmanagementtool, 可以用于management and monitorNode.jsapplication.
using步骤:
- installationPM2:
npm install -g pm2 - usingPM2启动application:
pm2 start server.js --name my-app - 查看applicationstatus:
pm2 status - 查看applicationlog:
pm2 logs my-app - 重启application:
pm2 restart my-app - 停止application:
pm2 stop my-app
4. Dockerdeployment
Docker is a containerization平台, 可以用于打package and deploymentapplication.
4.1 creationDockerfile
# usingNode.js官方镜像serving as构建environment
FROM node:16-alpine as build
# 设置工作Table of Contents
WORKDIR /app
# copypackage.json and package-lock.json
COPY package*.json ./
# installation依赖
RUN npm ci
# copysourcescode
COPY . .
# 构建application
RUN npm run build
# usingNginxserving asproduceenvironment
FROM nginx:alpine
# copy构建 after 静态file to Nginx 网站根Table of Contents
COPY --from=build /app/build /usr/share/nginx/html
# copyNginxconfigurationfile
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 暴露端口
EXPOSE 80
# 启动Nginx
CMD ["nginx", "-g", "daemon off;"]
4.2 creationNginxconfigurationfile
# nginx.conf
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# cache静态resource
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
add_header Cache-Control "public, max-age=31536000";
}
}
4.3 构建 and runDockercontainers
# 构建Docker镜像
docker build -t my-react-app .
# runDockercontainers
docker run -d -p 80:80 --name my-react-app my-react-app
# 查看containersstatus
docker ps
# 查看containerslog
docker logs my-react-app
# 停止containers
docker stop my-react-app
# deletecontainers
docker rm my-react-app
5. deploymentbest practices
- usingCDN加速静态resource
- 启用HTTPS
- configurationcache策略
- 启用gzip压缩
- usingautomationdeployment流程
- monitorapplicationperformance and status
- 设置errormonitor and log收集
- 定期backupdata
6. continuous integration and 持续deployment (CI/CD)
usingCI/CDtool可以automation构建 and deployment流程, improvingDevelopmentefficiency and deploymentquality.
6.1 usingGitHub Actions
GitHub Actions is GitHubproviding CI/CDservice, 可以用于automation构建, test and deploymentapplication.
# .github/workflows/deploy.yml
name: deployment React App
on:
push:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: build the app
run: npm run build
- name: deployment to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
6.2 usingGitLab CI/CD
GitLab CI/CD is GitLabproviding CI/CDservice, 可以用于automation构建, test and deploymentapplication.
# .gitlab-ci.yml
image: node:16-alpine
stages:
- build
- deploy
build:
stage: build
script:
- npm ci
- npm run build
artifacts:
paths:
- build
deploy:
stage: deploy
script:
- apk add --no-cache rsync sshpass
- sshpass -p $SERVER_PASSWORD rsync -avz build/ $SERVER_USER@$SERVER_HOST:/var/www/html/
only:
- main
练习 1: usingNetlifydeploymentReactapplication
- creation一个Reactapplication
- 将codepush to GitHub仓library
- usingNetlifydeploymentapplication
- verificationdeployment结果
练习 2: usingDockerdeploymentReactapplication
- creation一个Reactapplication
- creationDockerfile and Nginxconfigurationfile
- 构建Docker镜像
- runDockercontainers
- verificationdeployment结果