跳转到内容

Docker

前端容器化部署

步骤: 前端代码->构建->docker镜像->容器运行->nginx转发

nginx.conf

nginx
server {
  listen 80;
  server_name localhost;

  root /usr/share/nginx/html;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }

  location /api/ {
    proxy_pass http://backend:8080/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

Dockerfile

dockerfile
# 构建阶段
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# 运行阶段
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

验证

shell
docker build -t frontend-app .
docker run -p 8080:80 frontend-app
docker ps
docker logs frontend-app

浏览器访问:

text
http://localhost:8080

Will Try My Best.