vue的Docker默认模板

1.7k 词

docker 模板如下, 主要步骤如下

  1. 用 node14 作为镜像,打包前端文件
  2. 把上一个前端包,打进新的 nginx 镜像中

上述做法 1 点会留下一个无用的打包镜像,需要手动删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 使用node.js官方镜像作为基础镜像
FROM node:14 as build

# 设置淘宝镜像源为npm的默认镜像源
RUN npm config set registry https://registry.npm.taobao.org/

# 设置淘宝镜像源为yarn的默认镜像源
RUN yarn config set registry https://registry.npm.taobao.org/

# 设置工作目录
WORKDIR /app

# 将package.json和yarn.lock文件拷贝到工作目录
COPY package*.json yarn.lock ./

# 安装依赖
RUN yarn install

# 将当前目录下的源代码拷贝到工作目录
COPY . .

# 执行打包命令
RUN yarn build

# 使用nginx官方镜像作为基础镜像
FROM nginx:1.20

# 将编译好的文件拷贝到nginx的默认网站目录下
COPY --from=build /app/dist /usr/share/nginx/html

# 拷贝自定义的nginx配置文件到容器内
COPY ./conf/nginx.conf /etc/nginx/nginx.conf

# 暴露容器的80端口,允许外部访问
EXPOSE 80

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

nginx.conf 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
events {
worker_connections 1024;
}

http {
server {
listen 80;
server_name localhost;


root /usr/share/nginx/html/; # 根目录设置为/usr/share/nginx/html/

include mime.types;
default_type application/octet-stream;

#允许客户端跨域访问
# add_header Access-Control-Allow-Origin *;
# add_header Access-Control-Allow-Headers X-Requested-With;
# add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

sendfile on;

keepalive_timeout 65;

# 忽略favicon.ico请求
location = /favicon.ico {
log_not_found off;
access_log off;
}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|svg)$ {
expires 30d;
}

location ~ .*\.(js|css)?$ {
expires 12h;
}

location ~ /\. {
deny all;
}

# 路由配置
location / {
try_files $uri $uri/ /index.html;
}

# gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
}