月色真美

月色真美

Vue项目如何使用Docker进行部署发布

61
2024-04-24

1.编写Dockerfile脚本

FROM node:16.13.1 as builder
WORKDIR /pack
COPY package.json package-lock.json ./
RUN npm clean-install --registry=https://registry.npmmirror.com

FROM builder as publish
WORKDIR /app
COPY --from=builder /pack/node_modules node_modules
COPY ./ .
RUN npm run build:dev

FROM nginx:1.25.3
COPY --from=publish app/dist/ /usr/share/nginx/html/web/
EXPOSE 80
EXPOSE 443

注:上诉build:dev是本项目的构建命令,可根据各自项目自行变动;node和nginx基本镜像版本可自行变动

2.编写Docker-compose脚本

  test:
    build:
      context: $context_path
      dockerfile: $dockerfile_path
    container_name: test
    volumes:
      - /etc/localtime:/etc/localtime
      - $nginxconf_path:/etc/nginx/nginx.conf:ro
    networks:
      - backend
    restart: always

注:$context_path指代Dockerfile文件执行的上下文路径;$dockerfile_path指代Dockerfile文件的路径;$nginxconf_path指代nginx配置的路径(配置详情下文3所示);networks自行变动

3.编写Nginx脚本关键脚本

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip on;
    gzip_static on;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 5;
    gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;

    server {
		listen 80;
		listen [::]:80;
		server_name localhost;
	
		charset utf-8;
	     access_log /var/log/nginx/web.access.log main;
	     error_log /var/log/nginx/web.error.log;
	
		location / {
			root /usr/share/nginx/html/web;
			index index.html index.htm;
		}
	
		error_page   500 502 503 504  /50x.html;
		location = /50x.html {
	        root   /usr/share/nginx/html;
	    }
	}
}

注:此nginx脚本是vue项目本身的容器所用,并非外部代理

4.初次启动

docker-compose -f app.yml up -d

注:docker-compose脚本文件为app.yml时

5.更新发布

docker-compose -f app.yml up --build test -d

8.拉取代码并更新发布

# 拉取代码
cd /data/code/test_repository
git restore .
git pull --progress -v --no-rebase "origin"

# 构建
docker-compose -f app.yml up --build test -d