Docker容器化部署前端项目

159 阅读1分钟

目录

Project
├─ dist            # 打包后静态文件目录
├─ Dockerfile      # docker打包镜像配置文件
├─ nginx.template  # nginx配置模版文件
└─ ...

Dockerfile

无环境变量

# 使用 nginx:alpine 作为基础镜像
FROM nginx:alpine

# 将 dist 文件夹中的内容复制到 Nginx 默认的 web 根目录
COPY dist/ /usr/share/nginx/html/

# 如果你的前端应用使用路由,可能需要配置 Nginx 来支持前端路由
# 比如,使用 try_files 指令
COPY nginx.conf /etc/nginx/conf.d/default.conf

# 暴露 Nginx 默认端口
EXPOSE 80

# 启动 Nginx 服务
CMD ["nginx", "-g", "daemon off;"]

带环境变量(Nginx代理URL)

# 设置基础镜像
FROM nginx:alpine
# 将dist文件中的内容复制到 /app/dist 这个目录下面
COPY dist/  /app/dist
# 将nginx.template复制
COPY nginx.template /etc/nginx/conf.d
# 镜像端口
EXPOSE 80
# 指定工作目录
WORKDIR /etc/nginx/conf.d
# 将变量的写入
ENTRYPOINT envsubst '$URL' < nginx.template > default.conf && cat default.conf && nginx -g 'daemon off;'

nginx.template

server {
    listen       80;
    server_name  localhost;
    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/error.log  error;
    location / {
        root   /app/dist;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
  
    error_page   500 502 503 504  /50x.html;
    location /api/ {
        proxy_pass $URL; 
    }
}

打包docker image命令

docker build -t <image-name>:<tag> .

运行服务

Docker run

docker run --name <container-name> -p 80:80 -e URL=<backend-url> smd-web

Docker-compose

version: '3'

networks:
  mynetwork:
    external: true

services:
  backend:
    ...
  
  ...

  frontend:
    image: <image-name>
    ports:
      - 80:80
    links:
      - backend:<alias>
    depends_on:
      - backend
    environment:
      - URL=http://<alias>:5000