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.pswp.cn/bicheng/73150.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/73150.shtml
英文地址,請注明出處:http://en.pswp.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_…