SpringBoot项目构建为镜像并Docker部署(jar包和war包两种方式)

SpringBoot项目构建为镜像并Docker部署(jar包和war包两种方式)

使用SpringBoot构建一个简单的web项目,用于docker部署测试

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello,docker";
    }
}

一、jar包部署
1.打jar包
执行package,springboot默认生成jar包
2.上传阿里云服务器,编写dockerfile

#dockerfile脚本
FROM java:8
COPY *.jar /app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
#Dockerfile:dockerfile文件名
#springboot-jar:生成的镜像名称
docker build -f Dockerfile -t springboot-jar .
#生成镜像
[root@liuhongfei dockerfile] docker build -f Dockerfile -t springboot-jar .
Sending build context to Docker daemon  227.1MB
Step 1/4 : FROM java:8
 ---> d23bdf5b1b1b
Step 2/4 : COPY *.jar /app.jar
 ---> Using cache
 ---> 9f84126f4668
Step 3/4 : EXPOSE 8080
 ---> Using cache
 ---> a1d19cbfc206
Step 4/4 : ENTRYPOINT ["java","-jar","/app.jar"]
 ---> Using cache
 ---> c6e9acf2ad90
Successfully built c6e9acf2ad90
Successfully tagged springboot-jar:latest
[root@liuhongfei dockerfile] docker images
REPOSITORY         TAG       IMAGE ID       CREATED          SIZE
springboot-jar     latest    c6e9acf2ad90   19 hours ago     661MB
#启动容器,并访问/hello
[root@liuhongfei dockerfile] docker run -d --name springboot-jar -p 8080:8080 springboot-jar
7b726f9d725b321d8c0509521e26f5d83c4512aadd943f62c66621e88f54d285
[root@liuhongfei dockerfile] curl localhost:8080/hello
#访问成功
hello,docker
[root@liuhongfei dockerfile]# 

二、war包部署
war包部署的话,就需要在dockerfile中添加jdk和tomcat,并且在打包前修改springboot的打包方式为war,以及移除springboot自带的tomcat
1、编写dockerfile

FROM centos

MAINTAINER liuhongfei<2411107785@qq.com>

ADD jdk-8u144-linux-x64.tar.gz /usr/local
ADD apache-tomcat-8.5.69.tar.gz /usr/local
#添加war包到tomcat的webapps目录下
ADD dockertest-0.0.1-SNAPSHOT.war /usr/local/apache-tomcat-8.5.69/webapps

ENV mypath /usr/local
ENV JAVA_HOME /usr/local/jdk1.8.0_144
ENV CLASSPATH $JAVA_HOME/lib/
ENV CATALINA_HOME /usr/local/apache-tomcat-8.5.69
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/bin

WORKDIR $mypath

EXPOSE 8080

CMD /usr/local/apache-tomcat-8.5.69/bin/startup.sh && tail -f /usr/local/apache-tomcat-8.5.69/logs/catalina.out

2.将生成的war包上传到阿里云服务器,并生成镜像

#-f springboot-war:dockerfile文件名称
#-t springboot-war:生成的镜像名称
docker build -f springboot-war -t springboot-war .

3.启动容器并访问

[root@liuhongfei dockerfile]docker run -d --name springboot-war -p 8080:8080 springboot-war
4fdaa45528ef91441c1630f22afb55ec46213cc9bda1d8fec6cf43bf153d2dbc
[root@liuhongfei dockerfile]curl localhost:8080/dockertest-0.0.1-SNAPSHOT/hello
#访问成功
hello,docker
[root@liuhongfei dockerfile]#

你可能感兴趣的:(springboot构建镜像,docker部署,dockerfile)