需求
在基于SpringBoot + Vue的项目,有时需要把Vue的生成的静态资源,作为SpringBoot的资源文件来使用。
项目结构是这样的:一个后端项目back,一个前端项目vue,要生成一个运行于SpringBoot的镜像。
[root@htwy SpringBoot-Vue]# tree -L 2
.
├── back
│?? ├── pom.xml
│?? └── src
├── Dockerfile
├── README.md
└── vue
├── build
├── config
├── favicon.ico
├── index.html
├── package.json
└── src
6 directories, 6 files
实现
基本思路:基于多阶段构建方式
- 先把vue项目的代码构建成静态资源
- 把vue的静态资源存放于src/main/resources/public目录中,作为二阶段后端项目back的资源文件
- 得到back编译出的SpringBoot可运行jar: app.jar,放入基于jre环境的容器中即可。
# prepare stage - Compiling Vue
FROM node:9.11.1-alpine AS node-build
# make the 'app' folder the current working directory
WORKDIR /app
# copy both 'package.json' and 'package-lock.json' (if available)
COPY ./vue/package*.json ./
# install project dependencies
RUN npm install
# copy project files and folders to the current working directory (i.e. 'app' folder)
COPY ./vue .
# build app for production with minification
RUN npm run build
# First stage - Compiling application
FROM registry.cn-hangzhou.aliyuncs.com/acs/maven:3-jdk-8 AS build-env
ENV MY_HOME=/app
RUN mkdir -p $MY_HOME
WORKDIR $MY_HOME
ADD ./back/pom.xml $MY_HOME
# get all the downloads out of the way
RUN ["/usr/local/bin/mvn-entrypoint.sh","mvn","verify","clean","--fail-never"]
# add source
ADD ./back $MY_HOME
COPY --from=node-build /app/dist/* /$MY_HOME/src/main/resources/public
# run maven verify
RUN ["/usr/local/bin/mvn-entrypoint.sh","mvn","verify"]
# Second stage - build image
FROM openjdk:8-jre-alpine
COPY --from=build-env /app/target/*.jar /app.jar
ENV JAVA_OPTS=""
ENV SERVER_PORT 8080
EXPOSE ${SERVER_PORT}
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/urandom -jar /app.jar" ]
构建方法
[root@htwy SpringBoot-Vue]# docker build -t springboot-vue:v1 .
[root@htwy SpringBoot-Vue]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
springboot-vue v1 96528f2c8fc2 3 weeks ago 105MB
spring-back boot.1 2031e086927e 3 weeks ago 105MB
spring-vue httpd.1 66a6db579047 3 weeks ago 404MB