Dockerfile的多级构建springboot项目及运行(gradle)
本文章是基于gradle的,如果想要maven的方式,可以参考https://blog.csdn.net/Xavider/article/details/93722363
在Docker 17.05多阶段构建推出之后,我们只需要维护一个Dockerfile文件即可:
在项目的根目录下,创建如下的Dockerfile文件:
# First stage: complete build environment
FROM gradle:4.10.2-jdk8-alpine as builder
WORKDIR /home/gradle/
COPY . /home/gradle/
# package jar
RUN gradle --init-script ./init.gradle build -x test
# Second stage: minimal runtime environment
#FROM openjdk:8-jre
#FROM openjdk:8-jre-alpine
#FROM openjdk:8-jdk
#FROM openjdk:8-jdk-alpine
FROM amazoncorretto:8-alpine-jdk
## Change TimeZone
##-----------------------------------alpine------------------------------------------------------
## 安装 tzdata,复制里面的时区文件后删除 tzdata,保持精简
#RUN apk add --no-cache tzdata && \
# cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
# apk del tzdata && \
# echo "Asia/Shanghai" > /etc/timezone
##-----------------------------------ubuntu------------------------------------------------------
## 安装 tzdata,复制里面的时区文件后删除 tzdata,保持精简
#RUN apt update -y && \
# DEBIAN_FRONTEND="noninteractive" apt -y install tzdata
#RUN ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
# dpkg-reconfigure -f noninteractive tzdata
##-----------------------------------centos------------------------------------------------------
## 安装 tzdata,复制里面的时区文件后删除 tzdata,保持精简
#RUN rm -f /etc/localtime \
# && ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
# && echo "Asia/Shanghai" > /etc/timezone
# 设置 LABEL
LABEL maintainer="bydongxing@gmail.com"
# copy jar from the first stage
COPY --from=builder /home/gradle/build/libs/springboot-redis-*.jar /app.jar
ENV JAVA_OPTS=""
ENV PARAMS=""
# run jar
ENTRYPOINT [ "sh", "-c", "java -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar $PARAMS" ]
备注:
1、init.gradle
文件的内容:(地址可以换成自己的实际的maven仓库的地址
)
allprojects {
repositories {
maven {
url 'https://maven.aliyun.com/repository/public'
}
maven {
credentials {
username 'XXXX'
password 'XXXX'
}
url 'https://repo.rdc.aliyun.com/repository/40760-release-vOpnwm/'
}
maven {
credentials {
username 'XXXX'
password 'XXXXX'
}
url 'https://repo.rdc.aliyun.com/repository/40760-snapshot-RTWya3/'
}
}
}
2、启动命令
jvm层级: docker run -p 宿主机端口号:镜像端口号 -e JAVA_OPTS="-Dspring.profiles.active=dev -Dspring.redis.host=host.docker.internal" +镜像名称
Pagram层级: docker run -p 宿主机端口号:镜像端口号 -e PARAMS="--spring.profiles.active=dev --spring.redis.host=host.docker.internal" +镜像名称
其中host.docker.internal是容器访问宿主机的地址,也可以通过docker0的ip地址访问