1、准备工作
创建/sluse/mydockerfile/tomcat9目录,把需要的jdk、tomcat复制到该目录下,并且在该目录创建c.txt(演示COPY命令)
[root@localhost ~]# mkdir -p /sluse/mydockerfile/tomcat9 [root@localhost ~]# cd /sluse/mydockerfile/tomcat9 [root@localhost tomcat9]# touch c.txt
2、在上面目录创建Dockerfile
FROM centos MAINTAINER sl<shenlei_friend@163.com> #把宿主机当前上下文的c.txt拷贝到容器/usr/local/路径下 COPY c.txt /usr/local/cincontainer.txt #把java与tomcat添加到容器中 ADD jdk-8u201-linux-x64.tar.gz /usr/local/ ADD apache-tomcat-9.0.34.tar.gz /usr/local/ #安装vim编辑器 RUN yum -y install vim #设置工作访问时候的WORKDIR路径,登录落脚点 ENV MYPATH /usr/local WORKDIR $MYPATH #配置java与tomcat环境变量 ENV JAVA_HOME /usr/local/jdk1.8.0_201 ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.34 ENV CATALINA_BASE /usr/local/apache-tomcat-9.0.34 ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:CATALINA_HOME/bin #容器运行时监听的端口 EXPOSE 8080 #启动时运行tomcat #ENTRYPOINT ["/usr/local/pppp/bin/startup.sh"] #CMD ["/usr/local/ppp/bin/catalina.sh","run"] CMD /usr/local/apache-tomcat-9.0.34/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.34/bin/logs/catalina.out
3、构建镜像
没加 -f Dockerfile 会默认使用该文件
[root@localhost tomcat9]# docker build -t sltomcat9 .
构建完成如图:
4、运行
docker run -d -p 9080:8080 --name myt9 -v /slsluse/mydockerfile/tomcat9/test:/usr/local/apache-tomcat-9.0.34/webapps/test -v /slsluse/mydockerfile/tomcat9/tomcat9logs/:/usr/local/apache-tomcat-9.0.34/logs --privileged=true sltomcat9
验证容器卷已创建成功:
5、演示自定义tomcat 上发布程序
创建一个简单的项目,test/WEB-INF/web.xml;test/a.jsp
[root@localhost tomcat9]# cd /slsluse/mydockerfile/tomcat9/test [root@localhost test]# mkdir WEB-INF [root@localhost test]# cd WEB-INF [root@localhost WEB-INF]# vim web.xml [root@localhost WEB-INF]# cd .. [root@localhost test]# vim a.jsp
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>test</display-name> </web-app>
a.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>展示</title> </head> <body> -------------welcome---------------- <%="I am in docker tomcat self" %> <br> <br> <%System.out.print("docker tomcat self");%> </body> </html>
查看容器内数据已经同步:
docker exec 83be6cd8d052 ls -l /usr/local/apache-tomcat-9.0.34/webapps/test
重启容器,并访问查看结果:http://192.168.7.151:9080/test/a.jsp
docker restart 83be6cd8d052
查看日志已经记录:
[root@localhost tomcat9logs]# cd /slsluse/mydockerfile/tomcat9/tomcat9logs
[root@localhost tomcat9logs]# ll
[root@localhost tomcat9logs]# cat catalina.out
docker exec 83be6cd8d052 cat /usr/local/apache-tomcat-9.0.34/logs/catalina.out
在宿主机中修改a.jsp,同样不重启容器就能访问到修改的内容,如下: