服务器中使用Docker部署前端项目
一、准备前端项目
在项目终端使用命令打包
npm run build
然后在你的项目文件夹里面会有一个dist文件夹,这就是前端项目打包的产物。
二、上传dist到服务器
首先在服务器中使用命令创建frontend文件夹,后续关于前端打包的所有文件都放到这里面。
mkdir frontend
然后将dist文件夹上传到服务器,我这里选择scp命令上传
# 格式:scp -r 本地文件路径 服务器用户@服务器IP:服务器目标路径
# 1. 上传 dist 文件夹(-r 表示递归上传文件夹)
scp -r /本地项目路径/dist root@你的服务器IP:/path/to/frontend/# 2. 上传 Dockerfile(单个文件无需 -r)
scp /本地项目路径/Dockerfile root@你的服务器IP:/path/to/frontend/示例
scp -r F:\大三学年(下学期)\教室预约系统\后台管理端代码\ClassroomReservationSystem\dist root@10.253.9.100:/frontend
命令运行成功后会让你输入服务器的密码,此时输入密码即可上传。
出现下面的界面则是上传成功
三、服务器中使用docker部署前端项目
1、创建 Dockerfile
在项目根目录创建 Dockerfile
文件,内容如下:
# 阶段 1: 构建前端项目
FROM node:16-alpine as build-stage
WORKDIR /app
COPY package*.json ./
# 安装依赖
RUN npm install
# 复制源代码
COPY . .
# 构建生产版本
RUN npm run build# 阶段 2: 部署到 Nginx
FROM nginx:stable-alpine as production-stage
# 从构建阶段复制产物到 Nginx 服务目录
COPY --from=build-stage /app/dist /usr/share/nginx/html
# 复制自定义 Nginx 配置(可选)
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 暴露 80 端口
EXPOSE 80
# 启动 Nginx 服务
CMD ["nginx", "-g", "daemon off;"]
2、在 frontend
目录创建 Nginx 配置文件(含反向代理,对接后端)
在 frontend
目录下新建 nginx.conf
(用于配置 Nginx 静态资源路径和接口代理,避免前端请求后端跨域 / 404)
# 进入 frontend 目录(已在该目录可跳过)
cd /frontend# 创建并编辑 nginx.conf
vi nginx.conf
按 i
进入编辑模式,粘贴以下内容(关键修改后端地址 http://10.253.9.100:8080
为你的真实后端地址):
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80; # 容器内部端口(后续映射到服务器端口)server_name localhost;# 1. 托管前端静态资源(指向 dist 目录)location / {root /usr/share/nginx/html; # 容器内 dist 文件的存放路径index index.html index.htm;try_files $uri $uri/ /index.html; # 解决单页应用(SPA)刷新404问题}# 2. 反向代理:将 /api 开头的请求转发到后端(按需配置,无接口可删除)location /api/ {proxy_pass http://10.253.9.100:8080/; # 你的后端地址(IP+端口)proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
}
3、 构建 Docker 镜像
docker build -t your-project-name:latest .
your-project-name
是你的镜像名称latest
是标签(版本号)
示例:
docker build -t my-frontend:v1 .
4、运行 Docker 容器
使用以下命令启动容器:
docker run -d -p 8080:80 --name your-container-name your-project-name:latest
-d
:后台运行-p 8080:80
:将容器的 80 端口映射到主机的 8080 端口--name
:指定容器名称
示例:
docker run -d -p 3000:80 --name nginx-frontend my-frontend:v1
5、验证容器是否正常运行
docker ps | grep nginx-frontend
出现以下界面则说明容器正常运行
- 此时在本地浏览器访问
http://服务器IP:3000
,就能看到前端页面了!