Python和Docker实现AWS ECR/ECS上全自动容器化部署网站前端

以类似ChatGPT的网站前端界面的HTML页面、CSS样式表和JavaScript脚本为例,用Python代码将整个前端代码文件的目录,其中包括所有创建的前端代码文件用Docker打包成镜像文件,提前检查Docker软件是否已经安装,并如果容器服务不存在,则在Amazon ECR中注册容器服务,在Amazon ECS中上传对应的镜像文件并启动运行和返回运行状态,程序需要异常处理和日志文件记录每一次运行的参数和结果,所有运行所需的参数都存储在ini配置文件中。

这个解决方案提供了完整的CI/CD流水线基础框架,可以根据实际需求扩展自动化测试、蓝绿部署等高级功能。分步解决方案包含前端代码和部署脚本。以下是完整的实现:

  1. 前端代码文件结构:
chatgpt-frontend/
├── static/
│   ├── css/
│   │   └── style.css
│   └── js/
│       └── script.js
├── templates/
│   └── index.html
├── Dockerfile
├── requirements.txt
├── deploy.py
└── config.ini
  1. 前端代码文件内容:

static/css/style.css:

.chat-container {max-width: 800px;margin: 0 auto;padding: 20px;background-color: #f5f5f5;border-radius: 10px;height: 80vh;display: flex;flex-direction: column;
}.chat-messages {flex: 1;overflow-y: auto;padding: 10px;background-color: white;border-radius: 5px;margin-bottom: 10px;
}.message {margin: 10px 0;padding: 10px;border-radius: 5px;max-width: 70%;
}.user-message {background-color: #e3f2fd;margin-left: auto;
}.bot-message {background-color: #f5f5f5;
}.input-container {display: flex;gap: 10px;
}input[type="text"] {flex: 1;padding: 10px;border: 1px solid #ddd;border-radius: 5px;
}button {padding: 10px 20px;background-color: #007bff;color: white;border: none;border-radius: 5px;cursor: pointer;
}button:hover {background-color: #0056b3;
}

templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ChatGPT Clone</title><link rel="stylesheet" href="/static/css/style.css">
</head>
<body><div class="chat-container"><div class="chat-messages" id="chat-messages"><div class="message bot-message">Hello! How can I help you today?</div></div><div class="input-container"><input type="text" id="user-input" placeholder="Type your message..."><button onclick="sendMessage()">Send</button></div></div><script src="/static/js/script.js"></script>
</body>
</html>

static/js/script.js:

function appendMessage(message, isUser) {const chatMessages = document.getElementById('chat-messages');const messageDiv = document.createElement('div');messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;messageDiv.textContent = message;chatMessages.appendChild(messageDiv);chatMessages.scrollTop = chatMessages.scrollHeight;
}async function sendMessage() {const userInput = document.getElementById('user-input');const message = userInput.value.trim();if (message) {appendMessage(message, true);userInput.value = '';try {const response = await fetch('/api/chat', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ message })});const data = await response.json();appendMessage(data.reply, false);} catch (error) {appendMessage('Error connecting to the server', false);}}
}

Dockerfile:

FROM nginx:alpine
COPY ./static /usr/share/nginx/html/static
COPY ./templates /usr/share/nginx/html/templates
COPY ./templates/index.html /usr/share/nginx/html/index.html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

requirements.txt:

boto3==1.34.28
configparser==5.3.0
docker==6.1.3

config.ini:

[aws]
region = us-west-2
ecr_repository = chatgpt-frontend
ecs_cluster = ecs-cluster
ecs_service = chatgpt-frontend-service
task_definition = chatgpt-frontend-task[deployment]
image_name = chatgpt-frontend
image_tag = latest
port = 80

deploy.py:

import os
import subprocess
import configparser
import logging
import boto3
from docker import from_env
from docker.errors import DockerException
from botocore.exceptions import ClientError, NoCredentialsError# Configure logging
logging.basicConfig(filename='deployment.log',level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s'
)class DeploymentError(Exception):passclass AWSClients:def __init__(self, region):self.ecr = boto3.client('ecr', region_name=region)self.ecs = boto3.client('ecs', region_name=region)def load_config():config = configparser.ConfigParser()if not config.read('config.ini'):raise DeploymentError("Configuration file config.ini not found")return configdef check_docker():try:docker_client = from_env()docker_client.ping()logging.info("Docker is running")except DockerException:logging.error("Docker not installed or not running")raise DeploymentError("Docker not available")def build_docker_image(image_name, image_tag):try:client = from_env()image, build_logs = client.images.build(path='.',tag=f"{image_name}:{image_tag}",rm=True)logging.info(f"Successfully built image {image.tags}")return imageexcept DockerException as e:logging.error(f"Docker build error: {str(e)}")raise DeploymentError("Docker build failed")def push_to_ecr(aws_clients, image_name, image_tag):try:auth = aws_clients.ecr.get_authorization_token()username, password = auth['authorizationData'][0]['authorizationToken'].decode('utf-8').split(':')registry = auth['authorizationData'][0]['proxyEndpoint']client = from_env()client.login(username=username, password=password, registry=registry)ecr_image = f"{registry.replace('https://', '')}/{image_name}:{image_tag}"image = client.images.get(f"{image_name}:{image_tag}")image.tag(ecr_image)push_log = client.images.push(ecr_image)logging.info(f"Image pushed to ECR: {ecr_image}")return ecr_imageexcept ClientError as e:logging.error(f"AWS API error: {str(e)}")raise DeploymentError("ECR operation failed")def deploy_to_ecs(aws_clients, ecr_image, config):try:# Update task definitiontask_definition = {'family': config['deployment']['image_name'],'executionRoleArn': 'ecsTaskExecutionRole','containerDefinitions': [{'name': 'web','image': ecr_image,'portMappings': [{'containerPort': int(config['deployment']['port']),'hostPort': int(config['deployment']['port'])}],'essential': True}],'requiresCompatibilities': ['FARGATE'],'networkMode': 'awsvpc','cpu': '256','memory': '512'}response = aws_clients.ecs.register_task_definition(**task_definition)task_arn = response['taskDefinition']['taskDefinitionArn']logging.info(f"Registered task definition: {task_arn}")# Update serviceaws_clients.ecs.update_service(cluster=config['aws']['ecs_cluster'],service=config['aws']['ecs_service'],taskDefinition=task_arn,forceNewDeployment=True)logging.info("Service updated successfully")except ClientError as e:logging.error(f"ECS deployment error: {str(e)}")raise DeploymentError("ECS deployment failed")def main():try:config = load_config()aws_clients = AWSClients(config['aws']['region'])logging.info("Starting deployment process")# Docker operationscheck_docker()build_docker_image(config['deployment']['image_name'],config['deployment']['image_tag'])ecr_image = push_to_ecr(aws_clients,config['deployment']['image_name'],config['deployment']['image_tag'])# ECS deploymentdeploy_to_ecs(aws_clients, ecr_image, config)logging.info("Deployment completed successfully")print("Deployment successful! Service is updating...")except DeploymentError as e:logging.error(f"Deployment failed: {str(e)}")print(f"Error: {str(e)}")except Exception as e:logging.error(f"Unexpected error: {str(e)}")print(f"Unexpected error: {str(e)}")if __name__ == "__main__":main()

使用说明:

  1. 确保已安装以下依赖:
  • Docker
  • Python 3.8+
  • AWS CLI 配置好凭证
  1. 部署步骤:
# 安装Python依赖
pip install -r requirements.txt# 配置AWS凭证(如果尚未配置)
aws configure# 运行部署脚本
python deploy.py

这个实现包含以下功能:

  1. 前端界面:
  • 响应式聊天界面
  • 消息气泡显示
  • 用户输入和发送功能
  • 模拟API调用(需后端实现)
  1. 部署功能:
  • Docker镜像构建和推送
  • ECS服务更新
  • 完整的错误处理
  • 日志记录
  • 配置管理
  1. 安全特性:
  • AWS凭证安全管理
  • Docker安全构建
  • 安全组配置(需在AWS控制台预先配置)

注意:实际部署前需要完成以下准备工作:

  1. 在AWS创建ECR仓库
  2. 创建ECS集群和任务执行角色
  3. 配置VPC和安全组
  4. 在config.ini中填写正确的AWS资源配置

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

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

相关文章

无人机全景应用解析与技术演进趋势

无人机全景应用解析与技术演进趋势 ——从立体安防到万物互联的空中革命 一、现有应用场景全景解析 &#xff08;一&#xff09;公共安全领域 1. 立体安防体系 空中哨兵&#xff1a;搭载 77 GHz 77\text{GHz} 77GHz毫米波雷达&#xff08;探测距离 5 km 5\text{km} 5km&…

ChatGPT4.5详细介绍和API调用详细教程

OpenAI在2月27日发布GPT-4.5的研究预览版——这是迄今为止OpenAI最强大、最出色的聊天模型。GPT-4.5在扩大预训练和微调规模方面迈出了重要的一步。通过扩大无监督学习的规模&#xff0c;GPT-4.5提升了识别内容中的模式、建立内容关联和生成对于内容的见解的能力&#xff0c;但…

AI 中对内存的庞大需求

刚接触AI时&#xff0c;只知道AI对显存的要求很高&#xff0c;但慢慢发现&#xff0c;AI对内存的要求也越来越高了。 最近尝试玩下 wan 2.1 &#xff0c;进行图生视频&#xff0c;使用comfyui官方工作流&#xff0c;720p&#xff08;720*1280&#xff09;53帧&#xff0c;结果…

如何选择适合您智能家居解决方案的通信协议?

如何选择适合您智能家居解决方案的通信协议&#xff1f; 在开发智能家居产品时&#xff0c;选择合适的通信协议对于设备的高效运行及其在智能家居系统中的互操作性至关重要。市面上协议众多&#xff0c;了解它们的特性并在做决定前考虑各种因素是非常必要的。以下是一些帮助您…

L3-1 夺宝大赛

输入样例 1&#xff1a; 5 7 1 1 1 1 1 0 1 1 1 1 1 1 0 0 1 1 0 2 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 7 1 5 7 1 1 1 5 5 3 1 3 5 1 4输出样例 1&#xff1a; 7 6样例 1 说明&#xff1a; 七支队伍到达大本营的时间顺次为&#xff1a;7、不可能、5、3、3、5、6&#xff0c…

C# AOT生成的hellowwordEXE运行占用多少内存1-5MB?

C# 使用 AOT&#xff08;Ahead - Of - Time&#xff0c;提前编译&#xff09;生成的 "Hello, World!" 可执行文件在运行时占用的内存会受到多种因素的影响&#xff0c;以下是详细分析&#xff1a; 影响内存占用的因素 操作系统&#xff1a;不同的操作系统&#xff0…

nextJs在DOM视图中渲染未转为状态值的localStorage导致报错

报错但不限于如下&#xff1a; error: hydration failed because the initial ui does not match what was rendered on the server. Did not expect server HTML to contain a <span> in <div>. hook.js:608 warning: expected server html to contain a match…

macOS 安装 Homebrew、nvm 及安装切换 node 版本

一、安装Homebrew 提示&#xff1a;在安装 nvm 时&#xff0c;如果使用 brew 方式安装&#xff0c;就要先安装 Homebrew 1、打开终端&#xff0c;输入以下指令&#xff08;官网可获取最新命令&#xff09;&#xff1a; 国外镜像 /bin/bash -c "$(curl -fsSL https://ra…

海思高安主控芯片兼容编译fastboot流程

华为海思主控芯片有高安和非高安之分&#xff0c;主要是安全性上区别&#xff0c;启动程序不同&#xff0c;一般无法共用。但实际生产中可能出现混料或者同一款产品不同批次一个是高安的一个是非高安的&#xff0c;这时就需要软件上做兼容&#xff0c;实际是高安固件是可以做到…

大模型在甲状腺肿瘤预测及治疗方案制定中的应用研究

目录 一、引言 1.1 研究背景与意义 1.2 研究目的与创新点 1.3 研究方法与数据来源 二、甲状腺肿瘤概述 2.1 甲状腺肿瘤分类及特征 2.2 甲状腺肿瘤的发病率与危害 2.3 现有诊断与治疗手段概述 三、大模型技术原理与应用现状 3.1 大模型的基本原理与架构 3.2 大模型在…

Java学习——day20

文章目录 1. 异常处理与优化1.1 在文件操作中使用 try-catch1.2 try-with-resources 语法1.3 使用 finally 块关闭资源1.4 代码健壮性与优化 2. 实践任务2.1 改进思路2.2 示例改进要点2.3 检查点 3. 总结3.1 改进后的完整代码&#xff1a; 4. 今日生词 今日学习目标&#xff1a…

ajax组件是什么

在 Vue 项目中与后端接口通信&#xff0c;通常有以下几种常用的方式和组件&#xff1a; ### 1. **使用 Axios 进行 HTTP 请求** Axios 是一个基于 Promise 的 HTTP 客户端&#xff0c;适用于浏览器和 Node.js 环境。它支持请求和响应拦截、自动转换 JSON 数据、取消请求等功能…

C# WPF 基础知识学习(二)

四、数据绑定 &#xff08;一&#xff09;数据绑定基础 绑定源和目标&#xff1a;数据绑定建立了 UI 元素&#xff08;绑定目标&#xff09;属性与数据源&#xff08;绑定源&#xff09;之间的联系。例如&#xff0c;将一个TextBox的Text属性绑定到一个对象的某个属性上。绑定…

Trae AI IDEA安装与使用

文章目录 背景第一步、下载安装第二步、登录与使用优势异常处理 背景 最近比较热的 Trae 开发工具&#xff0c;在本地下载使用&#xff0c;记录下来。 第一步、下载安装 下载地址&#xff1a;【Trae中文版下载地址】&#xff0c;下载的安装文件名为&#xff1a;【Trae CN-Se…

Ubuntu22.04安装数据

数据库安装步骤&#xff1a; sudo apt-get update sudo apt install mysql-server mysql-client sudo systemctl start mysql sudo systemctl status mysql &#xff08;1&#xff09;在命令行登录 MySQL 数据库&#xff0c;并使用 mysql 数据库 &#xff08;必须使用这个…

【LangChain接入阿里云百炼deepseek】

这是目录 前言阿里云百炼注册账号使用代码执行结果 前言 大模型爆火&#xff0c;现在很多教程在教怎么使用大模型来训练Agent智能体&#xff0c;但是大部分教程都是使用的OpenAI。 最近阿里云推出DeepSeek-R1满血版&#xff0c;新用户可享100万免费Token额度。 今天就教大家怎…

火绒企业版V2.0全面支持Linux与国产化系统!免费试用助力国产化终端安全升级

国产化浪潮下的安全新挑战 随着信创产业的加速推进&#xff0c;国产操作系统&#xff08;统信UOS、麒麟OS等&#xff09;和ARM架构服务器逐步成为政企核心业务的基础设施。然而&#xff0c;针对国产化系统的勒索攻击、网页篡改、供应链漏洞等威胁频发&#xff0c;传统安全方案…

【HarmonyOS Next】鸿蒙加固方案调研和分析

【HarmonyOS Next】鸿蒙加固方案调研和分析 一、前言 根据鸿蒙应用的上架流程&#xff0c;本地构建app文件后&#xff0c;上架到AGC平台&#xff0c;平台会进行解析。根据鸿蒙系统的特殊设置&#xff0c;仿照IOS的生态闭环方案。只能从AGC应用市场下载app进行安装。这样的流程…

【前端拓展】Canvas性能革命!WebGPU + WebAssembly混合渲染方案深度解析

为什么需要混合方案&#xff1f; 真实场景痛点分析&#xff1a; 传统WebGL在高频数据更新时存在CPU-GPU通信瓶颈JavaScript的垃圾回收机制导致渲染卡顿复杂物理模拟&#xff08;如SPH流体&#xff09;难以在单线程中实现 技术选型对比&#xff1a; graph LRA[计算密集型任务…

win11编译llama_cpp_python cuda128 RTX30/40/50版本

Geforce 50xx系显卡最低支持cuda128&#xff0c;llama_cpp_python官方源只有cpu版本&#xff0c;没有cuda版本&#xff0c;所以自己基于0.3.5版本源码编译一个RTX 30xx/40xx/50xx版本。 1. 前置条件 1. 访问https://developer.download.nvidia.cn/compute/cuda/12.8.0/local_…