基于Dokcerfile实现haproxy、nginx以及tomcat小型站点

构建tomcat服务

tomcat/
├── tomcat-app1
│   ├── build-commit.sh
│   ├── Dockerfile
│   ├── myapp
│   │   └── index.jsp
│   ├── myapp.tar.gz
│   ├── run_tomcat.sh
│   └── server.xml
├── tomcat-app2
│   ├── build-commit.sh
│   ├── Dockerfile
│   ├── myapp
│   │   └── index.jsp
│   ├── myapp.tar.gz
│   ├── run_tomcat.sh
│   └── server.xml
└── tomcat-base-8.5.97
    ├── apache-tomcat-8.5.97.tar.gz
    ├── build-commit.sh
    ├── Dockerfile
    ├── jdk-8u401-linux-x64.tar.gz
    └── profile

构建tomcat镜像

Dockerfile

#tomcat base image
FROM centos:7.8.2003
​
ADD jdk-8u401-linux-x64.tar.gz /usr/local/src
​
RUN  ln -sv /usr/local/src/jdk1.8.0_401 /usr/local/jdk
RUN  ln -sv /usr/local/jdk/bin/java /usr/sbin/java
​
COPY profile /etc/profile
​
ENV JAVA_HOME /usr/local/jdk
ENV JRE_HOME $JAVA_HOME/jre
ENV CLASSPATH $JAVA_HOME/lib/:$JRE_HOME/lib/
ENV PATH $PATH:$JAVA_HOME/bin
​
ADD apache-tomcat-8.5.97.tar.gz /usr/local/src
​
RUN ln -sv /usr/local/src/apache-tomcat-8.5.97 /usr/local/src/tomcat
​
RUN rm -rf /etc/localtime && ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

profile

# /etc/profile
​
# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc
​
# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.
​
pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}
​
​
if [ -x /usr/bin/id ]; then
    if [ -z "$EUID" ]; then
        # ksh workaround
        EUID=`/usr/bin/id -u`
        UID=`/usr/bin/id -ru`
    fi
    USER="`/usr/bin/id -un`"
    LOGNAME=$USER
    MAIL="/var/spool/mail/$USER"
fi
​
# Path manipulation
if [ "$EUID" = "0" ]; then
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
fi
​
HOSTNAME=`/usr/bin/hostname 2>/dev/null`
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth
else
    export HISTCONTROL=ignoredups
fi
​
export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL
​
# By default, we want umask to get set. This sets it for login shell
# Current threshold for system reserved uid/gids is 200
# You could check uidgid reservation validity in
# /usr/share/doc/setup-*/uidgid file
if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
    umask 002
else
    umask 022
fi
​
for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then 
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done
​
unset i
unset -f pathmunge
​
export JAVA_HOME=/usr/local/jdk
export TOMCAT_HOME=/apps/tomcat
export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$TOMCAT_HOME/bin:$PATH
export CLASSPATH=.$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib:$JAVA_HOME/lib/tools.jar

build-command.sh

#!/bin/bash
​
docker build -t tomcat-centos-base:8.5.97 . 

运行测试

docker run -it --rm -p 8080:8080 tomcat-centos-base:8.5.97 bash
cd /usr/local/src/tomcat/ && ./bin/catalina.sh

tomcat-app1

../tomcat-app1/
├── build-command.sh
├── Dockerfile
├── myapp
│   └── index.jsp
├── myapp.tar.gz
├── run_tomcat.sh
└── server.xml

Dockerfile

#  tomcat app1
FROM tomcat-centos-base:8.5.97
​
ADD run_tomcat.sh /usr/local/src/tomcat/bin/run_tomcat.sh
ADD server.xml /usr/local/src/tomcat/conf/server.xml
ADD myapp.tar.gz /usr/local/src/tomcat/webapps
​
EXPOSE 8080 8443
​
#CMD ["/apps/tomcat/bin/catalina.sh", "run"]
CMD ["/usr/local/src/tomcat/bin/run_tomcat.sh"]
​

run_tomcat.sh

#!/bin/bash
/usr/local/src/tomcat/bin/catalina.sh start
tail -f /etc/hosts

server.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!-- APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <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>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               maxParameterCount="1000"
               />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               maxParameterCount="1000"
               />
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true"
               maxParameterCount="1000"
               >
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true"
               maxParameterCount="1000"
               >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector protocol="AJP/1.3"
               address="::1"
               port="8009"
               redirectPort="8443"
               maxParameterCount="1000"
               />
    -->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="/usr/local/src/tomcat/webapps" unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

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

myapp/indes.jsp

 cat myapp/index.jsp 
<h1>magedu m43 tomcat app web1 config</h1>

tar zcvf myapp.tar.gz myapp

build_command.sh

#!/bin/bash

docker build -t tomcat-app1:v1 .

tomcat-app2

与tomcat-app1不同的仅有index.jsp的内容

cat myapp/index.jsp 
<h1>magedu m43 tomcat app2 web config</h1>

tar zcvf myapp.tar.gz myapp

build_command.sh

#!/bin/bash

docker build -t tomcat-app2:v1 .

运行测试

docker run -it --rm -p 8081:8080 tomcat-app1:v1

docker run -it --rm -p 8082:8080 tomcat-app2:v1

构建nginx服务

nginx/
├── build_command.sh
├── code
│   └── index.html
├── code.tar.gz
├── Dockerfile
├── nginx-1.16.1.tar.gz
├── nginx.conf
└── run_nginx.sh

Dockerfile

#My Dockerfile
FROM centos:7.8.2003

RUN yum -y install epel-release && yum -y install vim wget tree lrzsz gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel iproute net-tools iotop

ADD nginx-1.16.1.tar.gz /usr/local/src

RUN cd /usr/local/src/nginx-1.16.1 && ./configure --prefix=/usr/local/nginx --with-http_sub_module && make && make install 

RUN cd /usr/local/nginx

ADD nginx.conf /usr/local/nginx/conf/nginx.conf

RUN useradd nginx -s /sbin/nologin

RUN ln -sv /usr/local/nginx/sbin/nginx /usr/sbin/nginx
ADD run_nginx.sh /usr/local/nginx/sbin/run_nginx.sh

EXPOSE 80 443

CMD ["/usr/local/nginx/sbin/run_nginx.sh"]

run_nginx.sh

#!/bin/bash
/usr/local/nginx/sbin/nginx
tail -f /etc/hosts

nginx.conf

#!/bin/bash
/usr/local/nginx/sbin/nginx
tail -f /etc/hosts
root@harbor:/opt/dockerfile/web/nginx# cat nginx
cat: nginx: No such file or directory
root@harbor:/opt/dockerfile/web/nginx# cat nginx.conf 

user  nginx;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    upstream web {
        server 192.168.59.5:8081;
        server 192.168.59.5:8082;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /usr/local/nginx/html;
            index  index.html index.htm;
        }

        location /myapp {
	        proxy_pass http://web;  
	    }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

build_command.sh

#!/bin/bash
docker build -t nginx_web:1.16.1 .

运行测试

docker run -it --rm -p 88:80 nginx_web:1.16.1

构建Haproxy

../haproxy/
├── build_command.sh
├── Dockerfile
├── haproxy-2.8.7.tar.gz
├── haproxy.cfg
└── run_haproxy.sh

Dockerfile

# build haproxy image
FROM centos:7.8.2003

RUN set -eux && yum -y install  libtermcap-devel ncurses-devel  libevent-devel readline-devel  gcc gcc-c++ glibc glibc-devel  pcre pcre-devel openssl openssl-devel  systemd-devel net-tools vim iotop bc zip unzip zlib-devel lrzsz tree   screen lsof tcpdump wget netdat 

ADD haproxy-2.8.7.tar.gz /usr/local/src

RUN cd /usr/local/src/haproxy-2.8.7 && make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy && mkdir /usr/local/haproxy/run  


ADD haproxy.cfg /etc/haproxy/

ADD run_haproxy.sh /usr/bin

EXPOSE 80 9999

CMD ["/usr/bin/run_haproxy.sh"]

run_haproxy.sh

#!/bin/bash

/usr/local/haproxy/sbin/haproxy -f /etc/haproxy/haproxy.cfg

tail -f /etc/hosts

haproxy.cfg

#全局配置:
#在配置文件的开头,可以设置一些全局的参数,如进程数、日志文件路径等。例如:
global
    log 127.0.0.1 local3 info
    chroot /usr/local/haproxy
#    stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
    stats timeout 30s
    uid 99
    gid 99
    daemon
    pidfile /usr/local/haproxy/run/haprxy.pid
   

#默认配置:
#可以设置一些默认的参数,如连接超时时间、负载均衡算法等。例如
defaults
    log global
    mode http
    option http-keep-alive
    option forwardfor
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

##前端配置:
##定义前端监听器,接收客户端请求,并将请求转发给后端服务器。可以指定监听的IP和端口,以及使用的协议。例如:
#
#frontend my_frontend
#    bind *:80
#    mode http
#    default_backend my_backend
#
#
##nst后端配置:
##定义后端服务器的列表和相关参数,如服务器的IP和端口、权重等。例如:
#
#backend my_backend
#    mode http
#    balance roundrobin
#    server server1 192.168.0.1:8080 weight 1 maxconn 100 check
#    server server2 192.168.0.2:8080 weight 2 maxconn 100 check
#
listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri     /haproxy-status
    stats auth    haadmin:123456
 
listen web_port
    bind 0.0.0.0:80
    mode http
    log global
    balance roundrobin 
    server web2   192.168.59.5:88   check inter 3000 fall 2 rise 5

build_command.sh

#!/bin/bash
docker build --progress=plain -t haproxy:v2.2.11  .

运行测试

docker run -it --rm -p 80:80 haproxy:v2.2.11  

访问http://192.168.59.5:80/myapp

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值