本文介绍Centos8发布React流程
安装Docker以及Nginx流程本文不做介绍,可以查看:
1.React项目打包:
以VSCode开发工具为例,新建终端,并运行`npm run build`命令
等待执行完毕后会在项目根目录出现dist文件夹,上传dist文件夹到linux服务器。
在自己的电脑上新建一个Dockerfile文件,没有后缀名。添加如下代码配置:
# 设置基础镜像 FROM nginx:alpine
将dist文件中的内容复制到 /usr/share/nginx/html/ 这个目录下面
COPY . /usr/share/nginx/html/
把Dockerfile文件上传到刚刚的dist文件夹中
执行命令切换到dist目录:
cd /app/dist
创建容器:
docker build -t 容器名 . //.一点要有
创建容器镜像:
docker run --name=reactdocker -p 8036:80 -d reactdocker //--name :指定容器名称。 --p :指定容器端口。--d :指定容器后台运行。
之后在输入`curl localhost:8036`指令查看镜像是否运行成功:
出现如上前端代码块代表成功!
2.配置Nginx:
执行指令`cd /usr/local`切换到local文件夹
继续执行`vi /usr/local/nginx/conf/nginx.conf`打开nginx配置文件
在文件中找到server节点,之后进行如下配置:
server {
listen 9111; #监听9111端口
server_name localhost;
client_max_body_size 10m; #请求最大字节限制
proxy_connect_timeout 300;#代理连接超时时间
proxy_read_timeout 300;#代理接收超时时间
location / {
root /app/dist;#前端文件夹路径
index index.html,index.htm;#初始页面
proxy_pass http://localhost:8036;#未携带api代表前端访问,9111重定向到8036,8036端口指前端发布到服务器的端口
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://localhost:8003;#携带api代表访问后端,9111重定向到8003,8003端口指后端发布到服务器的端口
}
#error_page 404 /404.html;
redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
此配置包含前后端!
需要注意的是这里!
root后面跟的是前端dist文件夹的路径,注意修改!
配置好之后执行
/usr/local/nginx/sbin/nginx -s reload
指令重启nginx
配置好之后执行指令,
curl localhost:9111
如出现和
curl localhost:8036
同样的代码块,即为成功。之后开启服务器外网端口9111,就可以通过外网访问了!