aws(学习笔记第三十四课) dockerized-app with asg-alb

文章目录

  • aws(学习笔记第三十四课) dockerized-app with asg-alb
  • 学习内容:
    • 1. 整体架构
      • 1.1 代码链接
      • 1.2 代码手动修改部分
        • 1.2.1 `rds_stack.py`
        • 1.2.2 `efs_stack.py`
        • 1.2.3 `asg_stack.py`
        • 1.2.4 `userdata.sh`
      • 1.2 整体架构
    • 2.代码解析
      • 2.1 全体`app.py`
      • 2.2 `NetworkStatck`网络
      • 2.3 `MySQL`数据库
      • 2.4 创建`efs`
      • 2.5 对`efs`创建`mount target`
    • 3.部署执行
      • 3.1.部署`NetworkStack`
      • 3.2.部署`RDSStack`
      • 3.3.部署`StorageStack`
      • 3.4 修改`userdata.sh`文件
      • 3.5 最后部署`ASGStack`

aws(学习笔记第三十四课) dockerized-app with asg-alb

  • 使用cdk生成dockerized-app并使用AutoScalingGroupApplicationLoaderBalancer

学习内容:

  • 使用cdk生成dockerized-app并使用AutoScalingGroupApplicationLoaderBalancer
  • AutoScalingGroup中使用efs以及RDS

1. 整体架构

1.1 代码链接

代码链接(docker-app-with-asg-alb)

1.2 代码手动修改部分

这里的代码没有完全实现是理想的部署就能运行,需要修改几个地方。

1.2.1 rds_stack.py

修改instance_type=ec2.InstanceType.of这里的参数。不修改的话创建数据库运行失败。在这里插入图片描述
修改后的代码:

from aws_cdk import (aws_rds as rds,aws_ec2 as ec2,RemovalPolicy, Stack)
from constructs import Constructclass RDSStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)# Creates a security group for AWS RDSsg_rds = ec2.SecurityGroup(self,id="sg_rds",vpc=props['vpc'],security_group_name="sg_rds")# Adds an ingress rule which allows resources in the VPC's CIDR# to access the database.sg_rds.add_ingress_rule(peer=ec2.Peer.ipv4("10.0.0.0/16"),connection=ec2.Port.tcp(3306))# Master username is 'admin' and database password is automatically# generated and stored in AWS Secrets Managermy_sql = rds.DatabaseInstance(self, "RDS",engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_39),vpc=props['vpc'],port=3306,instance_type=ec2.InstanceType.of(ec2.InstanceClass.R7G,ec2.InstanceSize.LARGE,),removal_policy=RemovalPolicy.DESTROY,security_groups=[sg_rds])
1.2.2 efs_stack.py

修改了efs创建和security group的创建顺序
在这里插入图片描述
修改后的代码:

from aws_cdk import (aws_efs as efs,aws_ec2 as ec2,Stack)
from constructs import Constructclass StorageStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)sg_efs = ec2.SecurityGroup(self,id="sg_efs",vpc=props['vpc'],security_group_name="sg_efs")sg_efs.add_ingress_rule(peer=ec2.Peer.ipv4("10.0.0.0/16"),connection=ec2.Port.tcp(2049))elasticfilestore = efs.CfnFileSystem(self, "efs-storage",encrypted=False,lifecycle_policies=None# security_group_ids=[sg_efs.security_group_id])
1.2.3 asg_stack.py

这里主要是因为AutoScalingGroup默认使用的是config方式来创建,但是最新版aws已经不支持config方式,这里主要改成launchTemplate方式。而且AutoScalingGroup启动的ec2是在private subnet,因此,需要public ec2进行访问,这里Allows only the IP of "123.123.123.123"换成自己的公网的ec2
在这里插入图片描述

from aws_cdk.aws_ec2 import SubnetType
from aws_cdk import (aws_ec2 as ec2,aws_autoscaling as autoscaling,aws_elasticloadbalancingv2 as elbv2,Stack)
from constructs import Constructclass ASGStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)userdata_file = open("./userdata.sh", "rb").read()# Creates a userdata object for Linux hostsuserdata = ec2.UserData.for_linux()# Adds one or more commands to the userdata object.userdata.add_commands(str(userdata_file, 'utf-8'))# Creates a security group for our applicationsg_nextcloud = ec2.SecurityGroup(self,id="sg_nextcloud",vpc=props['vpc'],security_group_name="sg_nextcloud")# Allows only the IP of "123.123.123.123"# to access this security group for SSHsg_nextcloud.add_ingress_rule(peer=ec2.Peer.ipv4("18.183.236.249/32"),connection=ec2.Port.tcp(22))# create launch templatelaunch_template = ec2.LaunchTemplate(self, "MyLaunchTemplate",machine_image=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2),instance_type=ec2.InstanceType.of(ec2.InstanceClass.MEMORY5, ec2.InstanceSize.XLARGE),security_group=sg_nextcloud,user_data=userdata,key_name="***", # )asg = autoscaling.AutoScalingGroup(self,"app-asg",vpc=props['vpc'],vpc_subnets=ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE_WITH_NAT),launch_template=launch_template,min_capacity=1,max_capacity=3,)# Creates a security group for the application load balancersg_alb = ec2.SecurityGroup(self,id="sg_alb",vpc=props['vpc'],security_group_name="sg_alb")# Allows connections from security group "sg_alb"# inside the "sg_nextcloud" security group to access port 8080# where our app listenssg_nextcloud.connections.allow_from(sg_alb, ec2.Port.tcp(8080), "Ingress")# Creates an application load balancelb = elbv2.ApplicationLoadBalancer(self,"ALB",vpc=props['vpc'],security_group=sg_alb,internet_facing=True)listener = lb.add_listener("Listener", port=80)# Adds the autoscaling group's (asg) instance to be registered# as targets on port 8080listener.add_targets("Target", port=8080, targets=[asg])# This creates a "0.0.0.0/0" rule to allow every one to access the# applicationlistener.connections.allow_default_port_from_any_ipv4("Open to the world")
1.2.4 userdata.sh

这里主要修改docker-compose的版本,因为太低的版本已经不支持了。
另外DB的设置,要根据实际的RDSStack创建的DB进行重新设置。后面会详细说明。
在这里插入图片描述

#!/bin/shyum install docker -y
yum install -y amazon-efs-utils# makes a directory
mkdir /nextclouddata
mount -t efs fs-d48c7f8c:/ /nextclouddata# enable and start docker
systemctl enable docker
systemctl start docker# bootstraps "docker compose"
yum install libxcrypt-compat
curl -L "https://github.com/docker/compose/releases/download/v2.34.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
usermod -aG docker ec2-user# Gets local-persist
curl -fsSL https://raw.githubusercontent.com/CWSpear/local-persist/master/scripts/install.sh | bash
docker volume create -d local-persist -o mountpoint=/nextclouddata/nextcloud-data --name=nextcloud-data# Heredoc for a docker-compose.yaml file
cat << 'EOF' > /home/ec2-user/docker-compose.yaml
version: '2'volumes:nextcloud-data:external: trueservices:app:image: nextcloudports:- 8080:80volumes:- nextcloud-data:/var/www/htmlrestart: alwaysenvironment:- MYSQL_DATABASE=nextcloud- MYSQL_USER=admin- MYSQL_PASSWORD=bflbfl1980314- MYSQL_HOST=nextcloud.csetrrtzbxti.ap-northeast-1.rds.amazonaws.com
EOFdocker-compose -f /home/ec2-user/docker-compose.yaml up

1.2 整体架构

在这里插入图片描述
这里,整体的架构已经被分为四个stack,并且其他三个stack都依赖NetworkStack
在这里插入图片描述

  • 首先构建网络,VPCpublic subnet以及private subnet,之后构筑MySQL数据库,以及EFS存储,最后构建AutoScalingGroup以及ApplicationLoaderBalancerAutoScalingGroup需要每个主机共享存储,所以需要构建EFS

2.代码解析

2.1 全体app.py

props = {'namespace': 'NetworkStack '}
app = App()
ns = NetworkStack(app, "NetworkStack", props)rds = RDSStack(app, "RDSStack", ns.outputs)
rds.add_dependency(ns)asg = ASGStack(app, "ASGStack", ns.outputs)
asg.add_dependency(ns)efs = StorageStack(app, "StorageStack", ns.outputs)
app.synth()

每个stack独立定义,都可以独立执行,也可以-all进行执行。

cdk --require-approval never deploy -all
cdk --require-approval never deploy NetworkStack
cdk --require-approval never deploy RDSStack
cdk --require-approval never deploy StorageStack
cdk --require-approval never deploy ASGStack

注意,这里后三个stack依赖NetowokStack

2.2 NetworkStatck网络

class NetworkStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)# Subnet configurations for a public and private tiersubnet1 = SubnetConfiguration(name="Public",subnet_type=SubnetType.PUBLIC,cidr_mask=24)subnet2 = SubnetConfiguration(name="Private",subnet_type=SubnetType.PRIVATE_WITH_NAT,cidr_mask=24)vpc = Vpc(self,"TheVPC",cidr="10.0.0.0/16",enable_dns_hostnames=True,enable_dns_support=True,max_azs=2,nat_gateway_provider=NatProvider.gateway(),nat_gateways=1,subnet_configuration=[subnet1, subnet2])# This will export the VPC's ID in CloudFormation under the key# 'vpcid'CfnOutput(self, "vpcid", value=vpc.vpc_id)# Prepares output attributes to be passed into other stacks# In this case, it is our VPC and subnets.self.output_props = props.copy()self.output_props['vpc'] = vpcself.output_props['subnets'] = vpc.public_subnets@propertydef outputs(self):return self.output_props

在这里插入图片描述

这里构建如下:

  • 构建整个vpc
  • 构建一个public subnet
  • 构建一个private subnet
  • vpcsubnet作为props参数保存起来。

2.3 MySQL数据库

class RDSStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)# Creates a security group for AWS RDSsg_rds = ec2.SecurityGroup(self,id="sg_rds",vpc=props['vpc'],security_group_name="sg_rds")# Adds an ingress rule which allows resources in the VPC's CIDR# to access the database.sg_rds.add_ingress_rule(peer=ec2.Peer.ipv4("10.0.0.0/16"),connection=ec2.Port.tcp(3306))# Master username is 'admin' and database password needs to be set after creationmy_sql = rds.DatabaseInstance(self, "RDS",engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_39),vpc=props['vpc'],port=3306,instance_type=ec2.InstanceType.of(ec2.InstanceClass.R7G,ec2.InstanceSize.LARGE,),removal_policy=RemovalPolicy.DESTROY,security_groups=[sg_rds])

构建的为绿框的部分。
在这里插入图片描述
主要构建如下:

  • RDS构建一个SecurityGroup
  • 设定ingress_rule
  • 之后构建RDS数据库

2.4 创建efs

因为AutoScalingGroup启动的多个ec2 instance都需要将/var/www/html使用相同的磁盘进行存储,所以要创建efs实现各个AutoScalingGroup启动的多个ec2 instance共享磁盘。

from aws_cdk import (aws_efs as efs,aws_ec2 as ec2,Stack)
from constructs import Constructclass StorageStack(Stack):def __init__(self, scope: Construct, id: str, props, **kwargs) -> None:super().__init__(scope, id, **kwargs)sg_efs = ec2.SecurityGroup(self,id="sg_efs",vpc=props['vpc'],security_group_name="sg_efs")sg_efs.add_ingress_rule(peer=ec2.Peer.ipv4("10.0.0.0/16"),connection=ec2.Port.tcp(2049))elasticfilestore = efs.CfnFileSystem(self, "efs-storage",encrypted=False,lifecycle_policies=None# security_group_ids=[sg_efs.security_group_id])

在这里插入图片描述
ec2efs进行mount如下图所示:
在这里插入图片描述

2.5 对efs创建mount target

aws(学习笔记第十一课) 使用AWS的EFS,以及AWS Storage Gateway,这里也对efs进行了详细的介绍。在ec2efs进行mount之前,需要对其创建挂载目标mount target可以认为,efs就是创建了一块磁盘,而创建挂载目标mount target就是对这块磁盘,又绑定了一个nfs server
在这里插入图片描述

3.部署执行

3.1.部署NetworkStack

cdk --require-approval never deploy NetworkStack

3.2.部署RDSStack

cdk --require-approval never deploy RDSStack

3.3.部署StorageStack

cdk --require-approval never deploy StorageStack

3.4 修改userdata.sh文件

根据生成的DBefs的具体值,重新设置userdata.sh文件。
在这里插入图片描述

3.5 最后部署ASGStack

cdk --require-approval never deploy ASGStack

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

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

相关文章

面试总结之 Glide自定义的三级缓存策略

一、为什么需要三级缓存&#xff1f; 在移动应用开发中&#xff0c;图片加载性能直接影响用户体验。根据 Google 统计&#xff0c;图片加载延迟超过 1 秒会导致 32% 的用户流失。传统图片加载方案存在以下痛点&#xff1a; 内存占用高&#xff1a;未压缩的大图直接占用大量内…

用Python实现交互式数据可视化:从基础图表到动态仪表板

用Python实现交互式数据可视化&#xff1a;从基础图表到动态仪表板 一、项目背景 本文将通过一个完整的Python项目&#xff0c;展示如何使用Plotly和ipywidgets构建从基础统计到动态交互的全栈数据可视化方案。 二、核心功能模块 1. 数据生成与预处理 np.random.seed(100)…

Linux进程信号

1.信号的认识 生活中例如闹钟&#xff0c;红绿灯&#xff0c;电话铃声等都属于信号&#xff0c;所白了信号就是中断我们正在做的事情&#xff0c;属于进行事件异步通知机制。 在Linux中信号是发给进程的&#xff0c;信号的产生相较于进程是异步的。 信号的相关知识点&#xff…

Java使用FFmpegFrameGrabber进行视频拆帧,结合Thumbnails压缩图片保存到文件夹

引入依赖 <dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.17</version></dependency><dependency><groupId>org.bytedeco</groupId><artifactId>ja…

c++项目-KV存储-模仿redis实现kv键值对存储的基本功能。

KV存储引擎的技术解析&#xff1a;数组、哈希与红黑树实现及其在网络I/O中的应用。 内容概要&#xff1a;本文档深入介绍了基于数组、哈希表和红黑树的键值存储引擎的设计与实现。文档首先阐述了系统的总体架构与类图关系&#xff0c;之后分别对底层存储结构进行了详细解释&am…

vue3:十一、主页面布局(优化页面跳转方式)

:router"true" 一、参考文章 vue3:十一、主页面布局(实现基本左侧菜单右侧内容效果)-CSDN博客 参考上述文章可知&#xff0c;页面跳转是通过在js中定义的菜单中携带的path&#xff0c;然后通过菜单的点击事件完成的跳转&#xff0c;现在可以进行优化&#xff0c;直…

深入解析 Java Stream API:筛选子节点的优雅实现!!!

&#x1f680; 深入解析 Java Stream API&#xff1a;筛选子节点的优雅实现 &#x1f527; 大家好&#xff01;&#x1f44b; 今天我们来聊聊 Java 8 中一个非常常见的操作&#xff1a;使用 Stream API 从 Map 中筛选出特定条件的元素。&#x1f389; 具体来说&#xff0c;我们…

统计学重要概念:自由度

在统计学中&#xff0c;自由度&#xff08;degrees of freedom&#xff0c;简称df&#xff09;是一个重要的概念&#xff0c;它表示在计算某个统计量时可以自由变化的值的数量。对于一个样本量为n的样本&#xff0c;自由度通常为n-1&#xff0c;这是因为我们需要用样本数据来估…

数据结构-排序

文章目录 1. 排序的概念2. 常见排序算法的实现2.1 插入排序1&#xff09;插入排序一&#xff09;基本思想二&#xff09;特性及时间复杂度三&#xff09;代码实现 2&#xff09;希尔排序&#xff08;缩小增量排序&#xff09;一&#xff09;基本思想二&#xff09;特性及时间复…

压缩壳学习

壳是什么 壳就是软件的一个保护套&#xff0c;防止软件被进行反编译或被轻易地修改。 其作用就是为了保护软件。 常见的大类壳有压缩壳、加密壳、VM 壳的分类。 压缩壳顾名思义就是用来减小软件的文件大小的&#xff1b;加密壳&#xff0c;通过加密软件来保护软件&#xff…

《AI大模型趣味实战》第6集:基于大模型和RSS聚合打造个人新闻电台

《AI大模型趣味实战》第6集&#xff1a;基于大模型和RSS聚合打造个人新闻电台 摘要 本文将带您探索如何结合AI大模型和RSS聚合技术&#xff0c;打造一个功能丰富的个人新闻电台系统。我们将使用Python和PyQt5构建一个桌面应用程序&#xff0c;该应用可以从多个RSS源抓取新闻&…

(学习总结29)Linux 进程概念和进程状态

Linux 进程概念 冯诺依曼体系结构软件运行与存储分级数据流动的理论过程 操作系统操作系统(Operator System) 概念操作系统的功能与作用系统调用和库函数概念 进程概念描述进程 - PCBtask_struct查看进程通过系统调用获取进程标示符 PID通过系统调用 fork 函数创建进程简单使用…

LLM - CentOS上离线部署Ollama+Qwen2.5-coder模型完全指南

文章目录 离线安装OllamaOllama下载Ollama硬件需求Ollama 常用命令参考Ollama安装Ollama 服务管理&开机启动开启局域网访问 Ollama 服务 离线安装模型gguf 文件格式下载Qwen2.5-Coder-7B-Instruct-GGUF格式选择 ( gguf 版本 )构建Modelfile文件加载并运行离线模型测试 集成…

Linux——信号

目录 Linux——信号1.信号的基础了解2.技术应用角度的信号3.产生信号3.1按键组合3.2系统调用产生信号3.2.1 kill()3.2.2 raise()3.2.3 abort() 3.3**.** 软件条件产生信号3.4硬件异常产生信号3.4.1 /0异常3.4.2 内存越界异常 4.理解信号的存在5.总结一下6.核心转储7.全部信号都…

向量叉积的应用——正反画画

1 解题思路 解题思路涉及的向量积相关知识 c实现 #include<iostream> #include<vector>using namespace std;struct TrianglePoint {int x;int y; };int momentForce(TrianglePoint A, TrianglePoint B, TrianglePoint C) {//AB向量&#xff1a;(B.x-A.x, B.y-A.…

构建自定义MCP天气服务器:集成Claude for Desktop与实时天气数据

构建自定义MCP天气服务器:集成Claude for Desktop与实时天气数据 概述 本文将指导开发者构建一个MCP(Model Control Protocol)天气服务器,通过暴露get-alerts和get-forecast工具,为Claude for Desktop等客户端提供实时天气数据支持。该方案解决了传统LLM无法直接获取天气…

Web安全策略CSP详解与实践

引言 &#xff1a;在黑客攻击频发的今天&#xff0c;你的网站是否像“裸奔”一样毫无防护&#xff1f;跨站脚本&#xff08;XSS&#xff09;、数据注入等攻击随时可能让用户数据泄露。今天我们将揭秘一个网站的隐形保镖——内容安全策略&#xff08;CSP&#xff09;&#xff0c…

HC-05与HC-06蓝牙配对零基础教程 以及openmv识别及远程传输项目的概述

这个是上一年的项目&#xff0c;之前弄得不怎么完整&#xff0c;只有一个openmv的&#xff0c;所以openmv自己去我主页找&#xff0c;这篇主要讲蓝牙 这个是我在使用openmv连接单片机1然后单片机1与单片机2通过蓝牙进行通信 最终实现的效果是&#xff1a;openmv识别到图形和数…

点云分割方法

点云分割 通过判断三维距离&#xff0c;实现对创建3团点云的分割 通过判断三维距离&#xff0c;实现对创建3团点云的分割 * 点云1 gen_object_model_3d_from_points (rand(100), rand(100),rand(100), Points1)* 点云2 gen_object_model_3d_from_points (rand(100), 2rand(100…

SpringBoot3使用CompletableFuture时java.util.ConcurrentModificationException异常解决方案

问题描述 在Spring Boot 3项目中&#xff0c;使用CompletableFuture进行异步编程时&#xff0c;偶发{"code":500,"msg":"java.util.ConcurrentModificationException"}异常&#xff0c;但代码中并未直接操作List或CopyOnWriteArrayList等集合类…