【云原生 | 53】Docker三剑客之Docker Compose应用案例一:Web负载均衡

🍁博主简介
        🏅云计算领域优质创作者
        🏅2022年CSDN新星计划python赛道第一名

        🏅2022年CSDN原力计划优质作者
        🏅阿里云ACE认证高级工程师
        🏅阿里云开发者社区专家博主

💊交流社区:CSDN云计算交流社区欢迎您的加入!

目录

1.web子目录 

1.1 index.py 

1.2 index.html 

1.3 Dockerfile 

2.haproxy子目录 

3.docker-compose.yml文件 

4.运行compose项目 

👑👑👑结束语👑👑👑

负载均衡器+Web应用是十分经典的应用结构。下面,博主将创建一个该结构的Web项目:将Haproxy作为负载均衡器,后端挂载三个Web容器。
首先创建一个haproxy_web目录,作为项目工作目录,并在其中分别创建两个子目录:web和haproxy。

1.web子目录 

在web子目录下将放置所需Web应用代码和Dockerfile,下面将生成需要的Web镜像。
这里用Python程序来实现一个简单的Web应用,该应用能响应HTTP请求,返回的页面将打印出访问者的IP和响应请求的后端容器的IP。

1.1 index.py 

编写一个index.py作为服务器文件,代码为:

#!/usr/bin/python
#authors: yeasy.github.com
#date: 2013-07-05
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import socket
import fcntl
import struct
import pickle
from datetime import datetime
from collections import OrderedDict
class HandlerClass(SimpleHTTPRequestHandler):def get_ip_address(self,ifname):s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915, # SIOCGIFADDRstruct.pack('256s', ifname[:15]))[20:24])def log_message(self, format, *args):if len(args) < 3 or "200" not in args[1]:returntry:request = pickle.load(open("pickle_data.txt","r"))except:request=OrderedDict()time_now = datetime.now()ts = time_now.strftime('%Y-%m-%d %H:%M:%S')server = self.get_ip_address('eth0')host=self.address_string()addr_pair = (host,server)if addr_pair not in request:request[addr_pair]=[1,ts]else:num = request[addr_pair][0]+1del request[addr_pair]request[addr_pair]=[num,ts]file=open("index.html", "w")file.write("<!DOCTYPE html> <html> <body><center><h1><font color=\"blue\"face=\"Georgia, Arial\" size=8><em>HA</em></font> Webpage VisitResults</h1></center>");for pair in request:if pair[0] == host:guest = "LOCAL: "+pair[0]else:guest = pair[0]if (time_now-datetime.strptime(request[pair][1],'%Y-%m-%d %H:%M:%S')).seconds < 3:file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"red\">"+str(request[pair][0])+ "</font> requests " + "from &lt<font color=\"blue\">"+guest+"</font>&gt to WebServer &lt<font color=\"blue\">"+pair[1]+"</font>&gt</p>")else:file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"maroon\">"+str(request[pair][0])+"</font> requests " + "from &lt<font color=\"navy\">"+guest+"</font>&gt to WebServer &lt<font color=\"navy\">"+pair[1]+"</font>&gt</p>")file.write("</body> </html>");file.close()pickle.dump(request,open("pickle_data.txt","w"))
if __name__ == '__main__':try:ServerClass = BaseHTTPServer.HTTPServerProtocol = "HTTP/1.0"addr = len(sys.argv) < 2 and "0.0.0.0" or sys.argv[1]port = len(sys.argv) < 3 and 80 or int(sys.argv[2])HandlerClass.protocol_version = Protocolhttpd = ServerClass((addr, port), HandlerClass)sa = httpd.socket.getsockname()print "Serving HTTP on", sa[0], "port", sa[1], "..."httpd.serve_forever()except:exit()

1.2 index.html 

生成一个临时的index.html文件,其内容会由index.py来更新:模板文件

$ touch index.html

1.3 Dockerfile 

生成一个Dockerfile,部署该Web应用,内容为:

FROM python:2.7
WORKDIR /code
ADD . /code
EXPOSE 80
CMD python index.py

2.haproxy子目录 

该目录将配置haproxy镜像。
在其中生成一个haproxy.cfg文件,内容为:
globallog 127.0.0.1 local0log 127.0.0.1 local1 noticemaxconn 4096
defaultslog globalmode httpoption httplogoption dontlognulltimeout connect 5000mstimeout client 50000mstimeout server 50000ms
listen statsbind 0.0.0.0:70mode httpstats enablestats hide-versionstats scope .stats realm Haproxy\ Statisticsstats uri /stats auth user:pass
frontend balancerbind 0.0.0.0:80mode httpdefault_backend web_backends
backend web_backendsmode httpoption forwardforbalance roundrobinserver weba weba:80 checkserver webb webb:80 checkserver webc webc:80 checkoption httpchk GET /http-check expect status 200

3.docker-compose.yml文件 

在haproxy_web目录下编写一个docker-compose.yml文件,该文件是Compose使用的主模板文件。其中,指定启动3个Web容器(weba、webb、webc),以及1个Haproxy容器:
# This will start a haproxy and three web services. haproxy will act as a
loadbalancer.
# Authors: yeasy.github.com
# Date: 2015-11-15
weba:build: ./webexpose:- 80
webb:build: ./webexpose:- 80
webc:build: ./webexpose:- 80
haproxy:image: haproxy:1.6volumes:- ./haproxy:/haproxy-override- ./haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:rolinks:- weba- webb- webcports:- "80:80"- "70:70"

4.运行compose项目 

现在haproxy_web目录应该长成下面的样子:

haproxy_web├── docker-compose.yml├── haproxy│ └── haproxy.cfg└── web├── Dockerfile├── index.html└── index.py
在该目录下执行sudo docker-compose up命令,控制台会整合显示出所有容器的输出信息:
$ sudo docker-compose up
Recreating haproxyweb_webb_1...
Recreating haproxyweb_webc_1...
Recreating composehaproxyweb_weba_1...
Recreating composehaproxyweb_haproxy_1...
Attaching to composehaproxyweb_webb_1, composehaproxyweb_webc_1, composehaproxyweb_weba_1, composehaproxyweb_haproxy_1

此时通过浏览器访问本地的80端口,会获取到页面信息,如图所示。

经过Haproxy自动转发到后端的某个Web容器上,刷新页面,可以观察到访问的容器地址的变化。
访问本地70端口,可以查看到Haproxy的统计信息,如下图所示。 查看本地的镜像,会发现Compose自动创建的haproxyweb_weba、 haproxyweb_webb、haproxyweb_webc镜像:

$ docker images
REPOSITORY          TAG         IMAGE ID         CREATED           VIRTUAL SIZE
haproxyweb_webb     latest      33d5e6f5e20b     44 minutes ago    675.2 MB
haproxyweb_weba     latest      33d5e6f5e20b     44 minutes ago    675.2 MB
haproxyweb_webc     latest      33d5e6f5e20b     44 minutes ago    675.2 MB
当然,还可以进一步使用Consul等方案来实现服务自动发现,这样就可以不用手动指定后端的web容器了,更为灵活。

👑👑👑结束语👑👑👑

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/7749.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django纪录操作之增删改查

一、单表 1、 添加记录 准备表 from django.db import modelsclass Book(models.Model):title models.CharField(max_length20)price models.DecimalField(max_digits65,decimal_places5)publish models.CharField(max_length30)pub_date models.DateTimeField(auto_now…

Python财经股票数据获取, 保存表格文件

目录标题 前言环境使用:模块使用]:代码展示尾语 前言 嗨喽~大家好呀&#xff0c;这里是魔王呐 ❤ ~! 环境使用: Python 3.8 解释器 Pycharm 编辑器 模块使用]: import requests —> 数据请求模块 pip install requests import csv 第三方模块安装: win R 输入cmd 输…

大数据Doris(五十):Export导出原理

文章目录 Export导出原理 一、原理 二、查询计划拆分 三、查询计划执行 Export导出原理 Doris Export、Select Into Outfile、MySQL dump三种方式数据导出。用户可以根据自己的需求导出数据。此外数据还可以以文件形式通过Borker备份到远端存储系统中&#xff0c;之后可以…

【Linux】Linux项目自动化构建工具-make/makefile

Linux项目自动化构建工具-make/makefile 什么是make/makefile&#xff1f;make/makefile的使用依赖关系依赖方法makefile是如何工作的&#xff1f;为什么要使用makefile呢&#xff1f;makefile是怎么做到的呢&#xff1f;make和make clean.PHONY&#xff1a;伪目标 特殊符号&am…

1 Prometheus-监控简介

目录 1 什么是监控 1.1 技术作为客户 1.2 业务作为客户 2. 监控基础知识 2.1 事后监控 2.2 机械式/模板式/无脑式监控 2.3 不够准确的监控 2.4 静态监控 2.5 不频繁的监控 2.6 缺少自动化或操作繁琐/不便 2.7 监控模式总结 3.监控机制 3.1 探针和内省 3.2 拉取和推…

LangChain大型语言模型(LLM)应用开发(二):Conversation Memory

LangChain是一个基于大语言模型&#xff08;如ChatGPT&#xff09;用于构建端到端语言模型应用的 Python 框架。它提供了一套工具、组件和接口&#xff0c;可简化创建由大型语言模型 (LLM) 和聊天模型提供支持的应用程序的过程。LangChain 可以轻松管理与语言模型的交互&#x…

Unity协程

unity提供了一种类似“多段代码并行执行”的功能&#xff0c;即协程。 我们在定义一个协程的时候&#xff0c;需要遵循类似这样的语法 IEnumerator&#xff08;枚举器接口&#xff09; namespace System.Collections {public interface IEnumerator{object Current { get; }/…

MySql基础知识及数据查询

目录 第一章 数据库概述 1.为什么要学习数据库&#xff1f; 2.数据库的相关概念 3.ORM(Object Relational Mapping)思想 4.表与表的记录之间存在哪些关联关系 第二章 基本的SELECT语句 1.SQL的分类 2. SQL基本规则 3.导入现有的数据表、表的数据 4.最基本的…

位图的详解

目录 位图 位图的概念 位图的实现 位图常见三道面试题 1.给定100亿个整数&#xff0c;设计算法找到只出现一次的整数&#xff1f; 2. 给两个文件&#xff0c;分别有100亿个整数&#xff0c;我们只有1G内存&#xff0c;如何找到两个文件交集&#xff1f; 3. 位图应用变形…

使用随便测测平台-做接口测试

目录 接口数据的来源 导出har文件 导入har文件 转化为用例 提取数据进行替换 如何选择哪些数据需要替换呢&#xff1f; Url Params、Data ​编辑进行替换操作 断言-冒烟 断言-详细 测试报告 结束 接口数据的来源 1、可通过charles工具&#xff0c;录制好接口操作&…

IDEA恢复误删除的文件

idea将删除的文件放在idea文件缓存中&#xff0c;文件的更改等信息都放在这个缓存中&#xff0c;所以短时间内删除的文件可以尝试恢复。

蚂蚁金服面试题解析:为什么String是HashMap中的绝佳Key类型?

大家好&#xff0c;我是小米&#xff0c;在今天的文章中&#xff0c;我将与大家一起探讨在使用HashMap时&#xff0c;选择使用String作为Key所带来的诸多好处。作为一位热爱技术的小伙伴&#xff0c;相信你一定对HashMap这个数据结构有所了解&#xff0c;那么&#xff0c;我们就…