当前位置:   article > 正文

Dockerfile 实战--nginx-tomcat-haproxy

Dockerfile 实战--nginx-tomcat-haproxy

一、Nginx 镜像构建

nginx 编译安装

环境准备:

../nginx/
├── build_command.sh
├── Dockerfile             Dockerfile 配置文件
├── nginx-1.16.1.tar.gz    源码安装包(这里使用1.16.1版本)
└── nginx.conf             配置文件

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
RUN useradd nginx -s /sbin/nologin
ADD nginx.conf /usr/local/nginx/conf/nginx.conf
​
RUN ln -sv /usr/local/nginx/sbin/nginx /usr/sbin/nginx
​
RUN echo "test nginx web" > /usr/local/nginx/html/index.html
​
EXPOSE 80 443
​
CMD ["nginx","-g","daemon off;"]

构建镜像执行文件

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

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;
​
    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;
        }
​
        #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;
        #}
    }
}
​

二、tomcat 镜像构建

环境准备

tomcat/
├── app1
│ ├── build_command.sh
│ ├── Dockerfile
│ ├── myapp.tar.gz
│ ├── run_tomcat.sh
│ └── server.xml
├── app2
│ ├── build_command.sh
│ ├── Dockerfile
│ ├── myapp
│ │ └── index.jsp
│ ├── myapp.tar.gz
│ ├── run_tomcat.sh
│ └── server.xml
├── centos
│ ├── build_command.sh
│ └── Dockerfile
├── jdk
│ └── jdk-8u-401
│     ├── build_command.sh
│     ├── Dockerfile
│     ├── jdk-8u401-linux-x64.tar.gz
│     └── profile
└── tomcat-8.5.97
    ├── apache-tomcat-8.5.97.tar.gz
    ├── build_command.sh
    └── Dockerfile
​

1、自制centos基础镜像

../centos/
├── build_command.sh
└── Dockerfile

Dockerfile

FROM centos:7.8.2003
​
RUN rpm -ivh http://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm && yum -y install vim wget tree lrzsz gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel iproute net-tools iotop
​
RUN groupadd www -g 2022 && useradd  -u 2022 -g 2022 www

build_command.sh

#!/bin/bash
​
docker build -t centos_web:7.2003 .

构建

chmod +x build_command.sh
./build_command.sh

2、自制jdk镜像-基于centos_web:7.2003

../../jdk/
└── jdk-8u-401
    ├── build_command.sh
    ├── Dockerfile
    ├── jdk-8u401-linux-x64.tar.gz
    └── profile

Dockerfile

FROM centos_web:7.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
ADD 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

build_command.sh

#!/bin/bash
​
docker build -t jdk_centos7_web:8u401 .

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 JRE_HOME $JAVA_HOME/jre
export TOMCAT_HOME=/usr/local/src/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

3、自制tomcat镜像

├── apache-tomcat-8.5.97.tar.gz
├── build_command.sh
└── Dockerfile

Dockerfile

FROM jdk_centos7_web:8u401
​
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

build_command.sh

#!/bin/bash
​
docker build -t tomcat_web:8.5.97 .

3.1 APP1

../app1/
├── build_command.sh
├── Dockerfile
├── myapp.tar.gz
├── run_tomcat.sh
└── server.xml

Dockerfile

FROM tomcat_web: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 ["/usr/local/src/tomcat/bin/run_tomcat.sh"]

build_command.sh

#!/bin/bash
​
docker build -t tomcat_app1:v1 .

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.tar.gz

mkdir myapp
​
cd myapp/
​
vim index.html
​
cat myapp/index.html 
<h1>magedu m43 tomcat app web config</h1>
​
tar zcvf myapp.tar.gz myapp/
myapp/
myapp/index.html

3.2 APP2

app2
├── build_command.sh
├── Dockerfile
├── myapp
│   └── index.jsp
├── myapp.tar.gz
├── run_tomcat.sh
└── server.xml

app2 有两处与app1 不同

build_command.sh

#!/bin/bash
​
docker build -t tomcat_app2:v1 .

myapp.tar.gz

tar zxvf myapp.tar.gz -C ./
vim myapp/index.html
cat myapp/index.html 
<h1>magedu m43 tomcat app2 web config</h1>
tar zcvf myapp.tar.gz myapp/

3.3 启动两个APP容器,测试页面

[root@localhost app1]# docker run -itd --name app1 -p 8081:8080 tomcat_app1:v1 
1d9ccc12288b1d12b0af293fd033c828531fb58bc460e1a383136120736a46b9
​
[root@localhost app1]# docker run -itd --name app2 -p 8082:8080 tomcat_app2:v1 
147ec5ab2123093c97b6f7dc71c279b8bfb0dc53afabac1ab3ff2c6a2e4378bc
​

image-20240304103551504

image-20240304103606727

三、haproxy镜像构建

环境准备

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

dockerfile

# build haproxy image
FROM centos_web:7.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"]

build_command.sh

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

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 web1   192.168.59.4:8081   check inter 3000 fall 2 rise 5
    server web2   192.168.59.4:8082   check inter 3000 fall 2 rise 5

测试运行

[root@localhost haproxy]# docker run -itd --name haproxy -p 80:80 -p 9999:9999 haproxy_web:v2.2.11 
a689872e921b598ad99039128df9e4b8273d07f0b02a54d503f3484ff8962ec8

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/298692
推荐阅读
相关标签
  

闽ICP备14008679号