基于alpine用dockerfile创建的tomcat镜像

Posted 一本正经的搞事情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于alpine用dockerfile创建的tomcat镜像相关的知识,希望对你有一定的参考价值。

1、下载alpine镜像

[[email protected] ~]# docker pull alpine
Using default tag: latest
Trying to pull repository docker.io/library/alpine ...
latest: Pulling from docker.io/library/alpine
4fe2ade4980c: Pull complete
Digest: sha256:621c2f39f8133acb8e64023a94dbdf0d5ca81896102b9e57c0dc184cadaf5528
Status: Downloaded newer image for docker.io/alpine:latest
[[email protected] ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/alpine latest 196d12cf6ab1 3 weeks ago 4.41 MB

2、通过dockerfile构建镜像

  在其他的资料中很多都是下载包然后在dockerfile 使用COPY进行拷贝,这里我就不这样做了,我们分开写(都是通过dockerfile进行构建镜像)

2.1.构建jdk镜像

  创建jdk目录

[[email protected] ~]# cd /opt/
[[email protected] opt]# mkdir -p alpine_jre && cd alpine_jre && touch Dockerfile
[[email protected] alpine_jre]# ll
总用量 0
-rw-r--r-- 1 root root 0 10月  6 17:39 Dockerfile

  编写dockerfile文件

# 基础镜像
FROM alpine

# 作者信息
MAINTAINER JRE Docker Maintainers "[email protected]"

# 修改源
RUN echo "http://mirrors.aliyun.com/alpine/latest-stable/main/" > /etc/apk/repositories &&     echo "http://mirrors.aliyun.com/alpine/latest-stable/community/" >> /etc/apk/repositories

# 安装需要的软件
RUN apk update &&     apk add --no-cache ca-certificates &&     apk add --no-cache curl bash tree tzdata &&     cp -rf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 定义环境变量
ENV PATH /usr/local/bin:${PATH}

# 安装JRE
RUN apk add --nocache openjdk8-jre-base &&     rm -rf /var/cache/apk/*

RUN {         echo ‘#!/bin/sh‘;         echo ‘set -e‘;         echo;         echo ‘dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"‘;      } > /usr/local/bin/docker-java-home     && chmod +x /usr/local/bin/docker-java-home

ENV JAVA_HOME /usr/lib/jvm/default-jvm
ENV PATH ${PATH}:${JAVA_HOME}/bin:${JAVA_HOME}/jre/bin
ENV JAVA_VERSION 8u71
ENV JAVA_ALPINE_VERSION 8.171.11-r0
RUN set -x         && apk add --no-cache         openjdk8-jre="$JAVA_ALPINE_VERSION" 

  创建镜像

[[email protected] alpine_jre]# docker build -t alpine_jre .

  查看镜像

[[email protected] alpine_jre]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
alpine_jre          latest              614bc57ab66e        33 seconds ago      91.1 MB
docker.io/alpine    latest              196d12cf6ab1        3 weeks ago         4.41 MB

 

2.2.构建tomcat镜像

  创建tomcat目录

[[email protected] ~]# cd /opt/
[[email protected] opt]# mkdir -p jre_tomcat && cd jre_tomcat && touch Dockerfile
[[email protected] jre_tomcat]# ll
总用量 0
-rw-r--r-- 1 root root 0 10月  6 17:46 Dockerfile

  编写dockerfile(基于上面的alpine_jre镜像)

#基础镜像
FROM alpine_jre

# 作者信息
MAINTAINER tomcat Docker Maintainers "[email protected]"

# 定义tomcat变量(如果有其他的可以在这里加)
ENV CATALINA_HOME /usr/local/tomcat
ENV PATH $CATALINA_HOME/bin:$PATH
RUN mkdir -p "$CATALINA_HOME"
WORKDIR $CATALINA_HOME

# let "Tomcat Native" live somewhere isolated
ENV TOMCAT_NATIVE_LIBDIR $CATALINA_HOME/native-jni-lib
ENV LD_LIBRARY_PATH ${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$TOMCAT_NATIVE_LIBDIR

RUN apk add --no-cache gnupg

# see http://archive.apache.org/dist/tomcat/tomcat-$TOMCAT_MAJOR/KEYS
# see also "update.sh" (https://github.com/docker-library/tomcat/blob/master/update.sh)
ENV GPG_KEYS 05AB33110949707C93A279E3D3EFE6B686867BA6 07E48665A34DCAFAE522E5E6266191C37C037D42 47309207D818FFD8DCD3F83F1931D684307A10A5 541FBE7D8F78B25E055DDEE13C370389288584E7 61B832AC2F1C5A90F0F9B00A1C506407564C17A3 713DA88BE50911535FE716F5208B0AB1D63011C7 79F7026C690BAA50B92CD8B66A3AD3F4F22C4FED 9BA44C2621385CB966EBA586F72C284D731FABEE A27677289986DB50844682F8ACB77FC2E86E29AC A9C5DF4D22E99998D9875A5110C01C5A2F6059E7 DCFD35E0BF8CA7344752DE8B6FB21E8933C60243 F3A04C595DB5B6A5F1ECA43E3B7BBB100D811BBE F7DA48BB64BCB84ECBA7EE6935CD23C10D498E23
RUN set -ex;         for key in $GPG_KEYS; do                 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key";         done

# 定义tomcat版本
ENV TOMCAT_MAJOR 8
ENV TOMCAT_VERSION 8.0.53

# 下载
# https://issues.apache.org/jira/browse/INFRA-8753?focusedCommentId=14735394#comment-14735394
ENV TOMCAT_TGZ_URL https://www.apache.org/dyn/closer.cgi?action=download&filename=tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz
# not all the mirrors actually carry the .asc files :‘(
ENV TOMCAT_ASC_URL http://archive.apache.org/dist/tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz.asc

# 安装
RUN set -x                 && apk add --no-cache --virtual .fetch-deps                 ca-certificates                 tar                 openssl         && wget -O tomcat.tar.gz "$TOMCAT_TGZ_URL"         && wget -O tomcat.tar.gz.asc "$TOMCAT_ASC_URL"         && gpg --batch --verify tomcat.tar.gz.asc tomcat.tar.gz         && tar -xvf tomcat.tar.gz --strip-components=1         && rm bin/*.bat         && rm tomcat.tar.gz*                 && nativeBuildDir="$(mktemp -d)"         && tar -xvf bin/tomcat-native.tar.gz -C "$nativeBuildDir" --strip-components=1         && apk add --no-cache --virtual .native-build-deps                 apr-dev                 dpkg-dev dpkg                 gcc                 libc-dev                 make                 "openjdk${JAVA_VERSION%%[-~bu]*}"="$JAVA_ALPINE_VERSION"                 openssl-dev         && (                 export CATALINA_HOME="$PWD"                 && cd "$nativeBuildDir/native"                 && gnuArch="$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)"                 && ./configure                         --build="$gnuArch"                         --libdir="$TOMCAT_NATIVE_LIBDIR"                         --prefix="$CATALINA_HOME"                         --with-apr="$(which apr-1-config)"                         --with-java-home="$(docker-java-home)"                         --with-ssl=yes                 && make -j$(getconf _NPROCESSORS_ONLN)                 && make install         )         && runDeps="$(                 scanelf --needed --nobanner --recursive "$TOMCAT_NATIVE_LIBDIR"                         | awk ‘{ gsub(/,/, "
so:", $2); print "so:" $2 }‘                         | sort -u                         | xargs -r apk info --installed                         | sort -u         )"         && apk add --virtual .tomcat-native-rundeps $runDeps         && apk del .fetch-deps .native-build-deps         && rm -rf "$nativeBuildDir"         && rm bin/tomcat-native.tar.gz

# verify Tomcat Native is working properly
RUN set -e         && nativeLines="$(catalina.sh configtest 2>&1)"         && nativeLines="$(echo "$nativeLines" | grep ‘Apache Tomcat Native‘)"         && nativeLines="$(echo "$nativeLines" | sort -u)"         && if ! echo "$nativeLines" | grep ‘INFO: Loaded APR based Apache Tomcat Native library‘ >&2; then                 echo >&2 "$nativeLines";                 exit 1;         fi

# 开发8080端口
EXPOSE 8080
# 执行命令
CMD ["catalina.sh", "run"]

  创建镜像

[[email protected] jre_tomcat]# docker build -t tomcat:1.0 .

  查看镜像

[[email protected] jre_tomcat]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
tomcat              1.0                 64c9cec4375d        7 seconds ago       124 MB
alpine_jre          latest              614bc57ab66e        8 minutes ago       91.1 MB
docker.io/alpine    latest              196d12cf6ab1        3 weeks ago         4.41 MB

  

2.3.构建tomcat_web镜像

  创建tomcat_web目录(包含Dockerfile和启动文件)

[[email protected] ~]# cd /opt/
[[email protected] opt]# mkdir tomcat_web && cd tomcat_web && touch Dockerfile && touch start.sh
[[email protected] tomcat_web]# ll
总用量 0
-rw-r--r-- 1 root root 0 10月  6 17:53 Dockerfile
-rw-r--r-- 1 root root 0 10月  6 17:53 start.sh

  编写start.sh启动脚本

#!/bin/sh

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# -----------------------------------------------------------------------------
# Control Script for the CATALINA Server
#
# Environment Variable Prerequisites
#
#   Do not set the variables in this script. Instead put them into a script
#   setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
#
#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.
#
#   CATALINA_OUT    (Optional) Full path to a file where stdout and stderr
#                   will be redirected.
#                   Default is $CATALINA_BASE/logs/catalina.out
#
#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc.
#
#   CATALINA_TMPDIR (Optional) Directory path location of temporary directory
#                   the JVM should use (java.io.tmpdir).  Defaults to
#                   $CATALINA_BASE/temp.
#
#   JAVA_HOME       Must point at your Java Development Kit installation.
#                   Required to run the with the "debug" argument.
#
#   JRE_HOME        Must point at your Java Runtime installation.
#                   Defaults to JAVA_HOME if empty. If JRE_HOME and JAVA_HOME
#                   are both set, JRE_HOME is used.
#
#   JAVA_OPTS       (Optional) Java runtime options used when any command
#                   is executed.
#                   Include here and not in CATALINA_OPTS all options, that
#                   should be used by Tomcat and also by the stop process,
#                   the version command etc.
#                   Most options should go into CATALINA_OPTS.
#
#   JAVA_ENDORSED_DIRS (Optional) Lists of of colon separated directories
#                   containing some jars in order to allow replacement of APIs
#                   created outside of the JCP (i.e. DOM and SAX from W3C).
#                   It can also be used to update the XML parser implementation.
#                   Defaults to $CATALINA_HOME/endorsed.
#
#   JPDA_TRANSPORT  (Optional) JPDA transport used when the "jpda start"
#                   command is executed. The default is "dt_socket".
#
#   JPDA_ADDRESS    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. The default is localhost:8000.
#
#   JPDA_SUSPEND    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. Specifies whether JVM should suspend
#                   execution immediately after startup. Default is "n".
#
#   JPDA_OPTS       (Optional) Java runtime options used when the "jpda start"
#                   command is executed. If used, JPDA_TRANSPORT, JPDA_ADDRESS,
#                   and JPDA_SUSPEND are ignored. Thus, all required jpda
#                   options MUST be specified. The default is:
#
#                   -agentlib:jdwp=transport=$JPDA_TRANSPORT,
#                       address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND
#
#   JSSE_OPTS       (Optional) Java runtime options used to control the TLS
#                   implementation when JSSE is used. Default is:
#                   "-Djdk.tls.ephemeralDHKeySize=2048"
#
#   CATALINA_PID    (Optional) Path of the file which should contains the pid
#                   of the catalina startup java process, when start (fork) is
#                   used
#
#   LOGGING_CONFIG  (Optional) Override Tomcat‘s logging config file
#                   Example (all one line)
#                   LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties"
#
#   LOGGING_MANAGER (Optional) Override Tomcat‘s logging manager
#                   Example (all one line)
#                   LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"
#
#   USE_NOHUP       (Optional) If set to the string true the start command will
#                   use nohup so that the Tomcat process will ignore any hangup
#                   signals. Default is "false" unless running on HP-UX in which
#                   case the default is "true"
# -----------------------------------------------------------------------------

# OS specific support.  $var _must_ be set to either true or false.
cygwin=false
darwin=false
os400=false
hpux=false
case "`uname`" in
CYGWIN*) cygwin=true;;
Darwin*) darwin=true;;
OS400*) os400=true;;
HP-UX*) hpux=true;;
esac

# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : ‘.*-> (.*)$‘`
  if expr "$link" : ‘/.*‘ > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

# Only set CATALINA_HOME if not already set
[ -z "$CATALINA_HOME" ] && CATALINA_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`

# Copy CATALINA_BASE from CATALINA_HOME if not already set
[ -z "$CATALINA_BASE" ] && CATALINA_BASE="$CATALINA_HOME"

# Ensure that any user defined CLASSPATH variables are not used on startup,
# but allow them to be specified in setenv.sh, in rare case when it is needed.
CLASSPATH=

if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then
  . "$CATALINA_BASE/bin/setenv.sh"
elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then
  . "$CATALINA_HOME/bin/setenv.sh"
fi

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
  [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
  [ -n "$JRE_HOME" ] && JRE_HOME=`cygpath --unix "$JRE_HOME"`
  [ -n "$CATALINA_HOME" ] && CATALINA_HOME=`cygpath --unix "$CATALINA_HOME"`
  [ -n "$CATALINA_BASE" ] && CATALINA_BASE=`cygpath --unix "$CATALINA_BASE"`
  [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi

# Ensure that neither CATALINA_HOME nor CATALINA_BASE contains a colon
# as this is used as the separator in the classpath and Java provides no
# mechanism for escaping if the same character appears in the path.
case $CATALINA_HOME in
  *:*) echo "Using CATALINA_HOME:   $CATALINA_HOME";
       echo "Unable to start as CATALINA_HOME contains a colon (:) character";
       exit 1;
esac
case $CATALINA_BASE in
  *:*) echo "Using CATALINA_BASE:   $CATALINA_BASE";
       echo "Unable to start as CATALINA_BASE contains a colon (:) character";
       exit 1;
esac

# For OS400
if $os400; then
  # Set job priority to standard for interactive (interactive - 6) by using
  # the interactive priority - 6, the helper threads that respond to requests
  # will be running at the same priority as interactive jobs.
  COMMAND=‘chgjob job(‘$JOBNAME‘) runpty(6)‘
  system $COMMAND

  # Enable multi threading
  export QIBM_MULTI_THREADED=Y
fi

# Get standard Java environment variables
if $os400; then
  # -r will Only work on the os400 if the files are:
  # 1. owned by the user
  # 2. owned by the PRIMARY group of the user
  # this will not work if the user belongs in secondary groups
  . "$CATALINA_HOME"/bin/setclasspath.sh
else
  if [ -r "$CATALINA_HOME"/bin/setclasspath.sh ]; then
    . "$CATALINA_HOME"/bin/setclasspath.sh
  else
    echo "Cannot find $CATALINA_HOME/bin/setclasspath.sh"
    echo "This file is needed to run this program"
    exit 1
  fi
fi

# Add on extra jar files to CLASSPATH
if [ ! -z "$CLASSPATH" ] ; then
  CLASSPATH="$CLASSPATH":
fi
CLASSPATH="$CLASSPATH""$CATALINA_HOME"/bin/bootstrap.jar

if [ -z "$CATALINA_OUT" ] ; then
  CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out
fi

if [ -z "$CATALINA_TMPDIR" ] ; then
  # Define the java.io.tmpdir to use for Catalina
  CATALINA_TMPDIR="$CATALINA_BASE"/temp
fi

# Add tomcat-juli.jar to classpath
# tomcat-juli.jar can be over-ridden per instance
if [ -r "$CATALINA_BASE/bin/tomcat-juli.jar" ] ; then
  CLASSPATH=$CLASSPATH:$CATALINA_BASE/bin/tomcat-juli.jar
else
  CLASSPATH=$CLASSPATH:$CATALINA_HOME/bin/tomcat-juli.jar
fi

# Bugzilla 37848: When no TTY is available, don‘t output to console
have_tty=0
if [ "`tty`" != "not a tty" ]; then
    have_tty=1
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
  JRE_HOME=`cygpath --absolute --windows "$JRE_HOME"`
  CATALINA_HOME=`cygpath --absolute --windows "$CATALINA_HOME"`
  CATALINA_BASE=`cygpath --absolute --windows "$CATALINA_BASE"`
  CATALINA_TMPDIR=`cygpath --absolute --windows "$CATALINA_TMPDIR"`
  CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
  JAVA_ENDORSED_DIRS=`cygpath --path --windows "$JAVA_ENDORSED_DIRS"`
fi

if [ -z "$JSSE_OPTS" ] ; then
  JSSE_OPTS="-Djdk.tls.ephemeralDHKeySize=2048"
fi
JAVA_OPTS="$JAVA_OPTS $JSSE_OPTS"

# Register custom URL handlers
# Do this here so custom URL handles (specifically ‘war:...‘) can be used in the security policy
JAVA_OPTS="$JAVA_OPTS -Djava.protocol.handler.pkgs=org.apache.catalina.webresources"

# Set juli LogManager config file if it is present and an override has not been issued
if [ -z "$LOGGING_CONFIG" ]; then
  if [ -r "$CATALINA_BASE"/conf/logging.properties ]; then
    LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties"
  else
    # Bugzilla 45585
    LOGGING_CONFIG="-Dnop"
  fi
fi

if [ -z "$LOGGING_MANAGER" ]; then
  LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"
fi

# Uncomment the following line to make the umask available when using the
# org.apache.catalina.security.SecurityListener
#JAVA_OPTS="$JAVA_OPTS -Dorg.apache.catalina.security.SecurityListener.UMASK=`umask`"

if [ -z "$USE_NOHUP" ]; then
    if $hpux; then
        USE_NOHUP="true"
    else
        USE_NOHUP="false"
    fi
fi
unset _NOHUP
if [ "$USE_NOHUP" = "true" ]; then
    _NOHUP=nohup
fi

# ----- Execute The Requested Command -----------------------------------------

# Bugzilla 37848: only output this if we have a TTY
if [ $have_tty -eq 1 ]; then
  echo "Using CATALINA_BASE:   $CATALINA_BASE"
  echo "Using CATALINA_HOME:   $CATALINA_HOME"
  echo "Using CATALINA_TMPDIR: $CATALINA_TMPDIR"
  if [ "$1" = "debug" ] ; then
    echo "Using JAVA_HOME:       $JAVA_HOME"
  else
    echo "Using JRE_HOME:        $JRE_HOME"
  fi
  echo "Using CLASSPATH:       $CLASSPATH"
  if [ ! -z "$CATALINA_PID" ]; then
    echo "Using CATALINA_PID:    $CATALINA_PID"
  fi
fi

if [ "$1" = "jpda" ] ; then
  if [ -z "$JPDA_TRANSPORT" ]; then
    JPDA_TRANSPORT="dt_socket"
  fi
  if [ -z "$JPDA_ADDRESS" ]; then
    JPDA_ADDRESS="localhost:8000"
  fi
  if [ -z "$JPDA_SUSPEND" ]; then
    JPDA_SUSPEND="n"
  fi
  if [ -z "$JPDA_OPTS" ]; then
    JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
  fi
  CATALINA_OPTS="$JPDA_OPTS $CATALINA_OPTS"
  shift
fi

if [ "$1" = "debug" ] ; then
  if $os400; then
    echo "Debug command not available on OS400"
    exit 1
  else
    shift
    if [ "$1" = "-security" ] ; then
      if [ $have_tty -eq 1 ]; then
        echo "Using Security Manager"
      fi
      shift
      exec "$_RUNJDB" "$LOGGING_CONFIG" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS         -Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" -classpath "$CLASSPATH"         -sourcepath "$CATALINA_HOME"/../../java         -Djava.security.manager         -Djava.security.policy=="$CATALINA_BASE"/conf/catalina.policy         -Dcatalina.base="$CATALINA_BASE"         -Dcatalina.home="$CATALINA_HOME"         -Djava.io.tmpdir="$CATALINA_TMPDIR"         org.apache.catalina.startup.Bootstrap "[email protected]" start
    else
      exec "$_RUNJDB" "$LOGGING_CONFIG" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS         -Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" -classpath "$CLASSPATH"         -sourcepath "$CATALINA_HOME"/../../java         -Dcatalina.base="$CATALINA_BASE"         -Dcatalina.home="$CATALINA_HOME"         -Djava.io.tmpdir="$CATALINA_TMPDIR"         org.apache.catalina.startup.Bootstrap "[email protected]" start
    fi
  fi

elif [ "$1" = "run" ]; then

  shift
  if [ "$1" = "-security" ] ; then
    if [ $have_tty -eq 1 ]; then
      echo "Using Security Manager"
    fi
    shift
    eval exec ""$_RUNJAVA"" ""$LOGGING_CONFIG"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS       -Djava.endorsed.dirs=""$JAVA_ENDORSED_DIRS"" -classpath ""$CLASSPATH""       -Djava.security.manager       -Djava.security.policy==""$CATALINA_BASE/conf/catalina.policy""       -Dcatalina.base=""$CATALINA_BASE""       -Dcatalina.home=""$CATALINA_HOME""       -Djava.io.tmpdir=""$CATALINA_TMPDIR""       org.apache.catalina.startup.Bootstrap "[email protected]" start
  else
    eval exec ""$_RUNJAVA"" ""$LOGGING_CONFIG"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS       -Djava.endorsed.dirs=""$JAVA_ENDORSED_DIRS"" -classpath ""$CLASSPATH""       -Dcatalina.base=""$CATALINA_BASE""       -Dcatalina.home=""$CATALINA_HOME""       -Djava.io.tmpdir=""$CATALINA_TMPDIR""       org.apache.catalina.startup.Bootstrap "[email protected]" start       >> "$CATALINA_OUT" 2>&1 
  fi
fi

  编写dockerfile(基于上面的tomcat镜像)

# 基础镜像
FROM tomcat:1.0

# 创建项目目录和日志目录,这个是要在宿主机-v挂载的
RUN set -x     &&mkdir -p /Webs/logs         &&rm -rf /usr/local/tomcat/logs         &&ln -sf /Webs/logs /usr/local/tomcat/logs

# 将启动文件copy到容器
COPY start.sh /usr/local/tomcat/bin/

# 给容器的启动脚本权限
RUN chmod +x /usr/local/tomcat/bin/start.sh

# 开放8080端口
EXPOSE 8080

# 运行tomcat
CMD ["start.sh","run"]

  创建镜像

[[email protected] tomcat_web]# docker build -t tomcat_web:v1 .

  查看镜像

[[email protected] tomcat_web]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
tomcat_web          v1                  b3651c50a7b5        26 seconds ago      124 MB
tomcat              1.0                 64c9cec4375d        6 minutes ago       124 MB
alpine_jre          latest              614bc57ab66e        14 minutes ago      91.1 MB
docker.io/alpine    latest              196d12cf6ab1        3 weeks ago         4.41 MB

3、创建容器

  创建项目目录

我们是基于tomcat_web镜像进行创建容器的
首先我先在宿主机上创建个项目的目录(server.xml的配置文件拷贝改路径就能用)
[[email protected] ~]# cd /home/
[[email protected] home]# mkdir test.tomcat.com && cd test.tomcat.com
[[email protected] test.tomcat.com]# touch server.xml  # 配置文件
[[email protected] test.tomcat.com]# mkdir logs        # 日志目录
[[email protected] test.tomcat.com]# mkdir wwwroot     # 项目主目录(要是修改了记得也在server.xml进行修改)
[[email protected] test.tomcat.com]# ll
总用量 0
drwxr-xr-x 2 root root 6 10月  6 18:03 logs
-rw-r--r-- 1 root root 0 10月  6 18:02 server.xml
drwxr-xr-x 2 root root 6 10月  6 18:03 wwwroot

  server.xml配置文件

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">
    <Connector port="8080" protocol="org.apache.coyote.http11.Http11AprProtocol"
               connectionTimeout="20000"
               maxThreads="1000" 
               minSpareThreads="100"  
               redirectPort="8443" URIEncoding="UTF-8"/>
    <Connector port="8009" maxThreads="1000" minSpareThreads="100"  protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="/Webs/wwwroot" unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="/Webs/wwwroot" reloadable="true" />
        <Valve className="org.apache.catalina.valves.AccessLogValve" 
        directory="logs" 
        prefix="localhost__access_log" 
        suffix=".txt" 
        pattern="%{X-Real-IP}i %l %u %t "%r" %s %b" />

      </Host>
         
    </Engine>
  </Service>
</Server>

  编写测试页面

在wwwroot中编写个测试页面
[[email protected] test.tomcat.com]# cd wwwroot/
[[email protected] wwwroot]# cat index.html 
成功了

  创建并启动容器

docker run -tid  --restart=always --name test.tomcat.com  -p 5081:8080 -v /home/test.tomcat.com/:/Webs -m 2048m  --memory-swap=2048m  --cpu-shares=256  tomcat_web:v1 start.sh  run -config /Webs/server.xml

  查看容器

[[email protected] test.tomcat.com]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
ab62045e0688        tomcat_web:v1       "start.sh run -con..."   2 seconds ago       Up 1 second         0.0.0.0:5081->8080/tcp   test.tomcat.com

  测试

[[email protected] test.tomcat.com]# curl 127.0.0.1:5081
成功了
[[email protected] test.tomcat.com]# 

4、温馨提示

1、各位肯定会问我问什么要做这么多的镜像,我的回答是每个都独立出来 放在之后的私有仓库中,以后可以单独的使用
2、这篇文章的代码都完全的可以直接的复制粘贴使用,要注意的是根据自己的情况来修改Dockerfile的变量版本,还有就是项目的路径和创建容器的参数
3、我们在创建第二个项目的使用,完全可以重复的执行创建容器的步骤只是修改下项目目录的名字和容器的名字而已
4、也可以把上面的三个dockerfile文件合并创建镜像,但是不建议这样做

 

以上是关于基于alpine用dockerfile创建的tomcat镜像的主要内容,如果未能解决你的问题,请参考以下文章

基于alpine用dockerfile创建的ssh镜像

基于Alpine 编写Haproxy的Dockerfile

Docker -- 自定义镜像(Dockerfile)基于Ubuntu镜像构建一个新镜像基于java:8-alpine镜像将一个Java项目构建为镜像

linux12企业实战 -- 06alpine Linux简介alpine制作jdk镜像jre镜像 Alpine 命令

docker制作alpine初始镜像

Alpine Dockerfile --no-cache Vs 的优势。 rm /var/cache/apk/*