欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

將Python Flask服務打包成Docker鏡像并運行的完整指南

 更新時間:2025年08月04日 10:03:36   作者:Firefire?  
在現(xiàn)代軟件開發(fā)中,容器化技術已經(jīng)成為部署應用程序的標準方式之一,Docker作為最流行的容器化平臺,能夠幫助開發(fā)者輕松打包、分發(fā)和運行應用程序,本文將詳細介紹如何將一個簡單的Python Flask服務打包成Docker鏡像并運行,需要的朋友可以參考下

前言

在現(xiàn)代軟件開發(fā)中,容器化技術已經(jīng)成為部署應用程序的標準方式之一。Docker作為最流行的容器化平臺,能夠幫助開發(fā)者輕松打包、分發(fā)和運行應用程序。本文將詳細介紹如何將一個簡單的Python Flask服務打包成Docker鏡像并運行。

準備工作

在開始之前,請確保你的系統(tǒng)已經(jīng)安裝了以下工具:
1.Docker(官方安裝指南
2.Python 3.x(可選,用于本地測試)

項目結(jié)構

我們的項目包含以下文件:

.
├── Dockerfile
├── .dockerignore
├── requirements.txt
└── wisdom_app.py

具體步驟

1. 創(chuàng)建Python Flask應用

首先,我們有一個簡單的Flask應用wisdom_app.py,它會隨機顯示編程名言和有趣的圖片。

import random
import os
from flask import Flask, render_template_string

app = Flask(__name__)

# 有趣的名言列表
quotes = [
    {"text": "Debugging is like being a detective in a crime movie where you are also the murderer.", "author": "Filipe Fortes"},
    {"text": "If you want your code to be fast, it should be easy to understand.", "author": "Brian Kernighan"},
    {"text": "The best thing about a boolean is even if you are wrong, you are only off by a bit.", "author": "Anonymous"},
    {"text": "There are two ways to write error-free programs; only the third one works.", "author": "Alan J. Perlis"},
    {"text": "Programming is like sex: One mistake and you have to support it for the rest of your life.", "author": "Michael Sinz"}
]

# 有趣的動物圖片URL列表
animal_images = [
    "https://picsum.photos/seed/funnycat/400/300",
    "https://picsum.photos/seed/lazydog/400/300",
    "https://picsum.photos/seed/sillyrabbit/400/300",
    "https://picsum.photos/seed/curiousgoat/400/300",
    "https://picsum.photos/seed/playfulpanda/400/300"
]

@app.route('/')
def get_random_wisdom():
    quote = random.choice(quotes)
    image_url = random.choice(animal_images)
    
    # 簡單的HTML模板,用于展示名言和圖片
    html_template = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>智慧之言</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
                text-align: center;
            }
            .quote-box {
                background-color: #f9f9f9;
                border-left: 10px solid #ccc;
                margin: 1.5em 10px;
                padding: 1em 20px;
                font-size: 1.2em;
                border-radius: 5px;
            }
            .author {
                color: #666;
                font-style: italic;
                margin-top: 10px;
            }
            .image-container {
                margin-top: 30px;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            img {
                max-width: 100%;
                height: auto;
            }
            button {
                background-color: #4CAF50;
                border: none;
                color: white;
                padding: 10px 20px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 16px;
                margin: 20px 2px;
                cursor: pointer;
                border-radius: 5px;
                transition: background-color 0.3s;
            }
            button:hover {
                background-color: #45a049;
            }
        </style>
    </head>
    <body>
        <h1>今日智慧</h1>
        <div class="quote-box">
            "{{ quote_text }}"
            <div class="author">- {{ quote_author }}</div>
        </div>
        <div class="image-container">
            <img src="{{ image_url }}" alt="有趣的動物">
        </div>
        <button onclick="window.location.reload()">換一條</button>
    </body>
    </html>
    """
    
    return render_template_string(
        html_template, 
        quote_text=quote["text"], 
        quote_author=quote["author"],
        image_url=image_url
    )

if __name__ == '__main__':
    # 獲取端口號,默認為5000
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

2. 創(chuàng)建requirements.txt

列出項目所需的Python依賴:

flask==2.3.2
importlib-metadata>=3.6.0
Werkzeug==2.3.7

3. 編寫Dockerfile(注意文件名沒有后綴)

Dockerfile是構建鏡像的核心文件,我們使用多階段構建來優(yōu)化鏡像大?。?/p>

# 使用完整的 Python 3.9 鏡像(基于 Debian Bullseye)
FROM python:3.9 AS builder

# 確保 sources.list 文件存在并覆蓋為阿里云鏡像源(Bullseye 版本)
RUN test -f /etc/apt/sources.list || touch /etc/apt/sources.list && \
    sed -i 's|deb.debian.org|mirrors.aliyun.com/debian|g' /etc/apt/sources.list && \
    sed -i 's|security.debian.org|mirrors.aliyun.com/debian-security|g' /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian/ bullseye main contrib non-free" > /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian/ bullseye-updates main contrib non-free" >> /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian-security bullseye-security main contrib non-free" >> /etc/apt/sources.list

# 安裝系統(tǒng)依賴(先清理緩存再更新)
RUN apt-get clean && \
    apt-get update && \
    apt-get install -y --no-install-recommends build-essential && \
    rm -rf /var/lib/apt/lists/*

# 升級 pip 并安裝依賴
RUN pip install --upgrade pip setuptools wheel && \
    pip install importlib-metadata>=3.6.0

# 復制并安裝 Python 依賴(使用阿里云 PyPI 源加速)
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt

# 最終運行鏡像
FROM python:3.9-slim

# 同樣切換為阿里云鏡像源(Bullseye 版本)
RUN test -f /etc/apt/sources.list || touch /etc/apt/sources.list && \
    sed -i 's|deb.debian.org|mirrors.aliyun.com/debian|g' /etc/apt/sources.list && \
    sed -i 's|security.debian.org|mirrors.aliyun.com/debian-security|g' /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian/ bullseye main contrib non-free" > /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian/ bullseye-updates main contrib non-free" >> /etc/apt/sources.list && \
    echo "deb http://mirrors.aliyun.com/debian-security bullseye-security main contrib non-free" >> /etc/apt/sources.list

# 安裝運行時依賴
RUN apt-get clean && \
    apt-get update && \
    apt-get install -y --no-install-recommends libgomp1 && \
    rm -rf /var/lib/apt/lists/*

# 復制構建產(chǎn)物和應用代碼
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.9/site-packages/ /usr/local/lib/python3.9/site-packages/
COPY wisdom_app.py .

# 暴露端口并啟動應用
EXPOSE 5000
ENV FLASK_APP=wisdom_app.py
CMD ["flask", "run", "--host=0.0.0.0"]

4. 創(chuàng)建.dockerignore文件

忽略不需要的文件,減小鏡像體積:

__pycache__
*.pyc
*.pyo
*.pyd
.venv
env

5. 構建Docker鏡像

打開cmd,cd到項目目錄,執(zhí)行以下命令構建鏡像:

docker build -t wisdom-app:latest .

參數(shù)說明:

-t wisdom-app:latest :為鏡像指定名稱和標簽
. :使用當前目錄中的Dockerfile

6. 運行Docker容器

構建完成后,可以使用以下命令運行容器:

docker run -it -p 5000:5000 wisdom-app:latest

或者使用:

docker run -it -p 5000:5000 wisdom-app:latest python -m flask run --host=0.0.0.0

參數(shù)說明:

-it:以交互模式運行容器
-p 5000:5000:將容器的5000端口映射到主機的5000端口
--host=0.0.0.0:允許外部訪問Flask應用

7. 測試應用

在瀏覽器中訪問http://localhost:5000,你應該能看到隨機顯示的名言和圖片。

8. 其他有用的Docker命令

查看運行中的容器:

docker ps

停止容器:

docker stop <容器ID>

刪除容器:

docker rm <容器ID>

刪除鏡像:

docker rmi wisdom-app:latest

進入運行中的容器:

docker exec -it <容器ID> /bin/bash

常見問題解決

端口沖突:如果5000端口已被占用,可以修改映射端口,如-p 5001:5000

構建緩慢:確保使用了國內(nèi)鏡像源(如阿里云),如Dockerfile中所示

容器立即退出:檢查應用是否有錯誤日志,使用docker logs <容器ID>查看

無法訪問應用:確保容器正確運行,并且防火墻允許對應端口的訪問

以上就是將Python Flask服務打包成Docker鏡像并運行的完整指南的詳細內(nèi)容,更多關于Python Flask打包成Docker鏡像的資料請關注腳本之家其它相關文章!

相關文章

  • Python利用pdfplumber庫提取pdf中表格數(shù)據(jù)

    Python利用pdfplumber庫提取pdf中表格數(shù)據(jù)

    pdfplumber是一個用于從PDF文檔中提取文本和表格數(shù)據(jù)的Python庫,它可以幫助用戶輕松地從PDF文件中提取有用的信息,例如表格、文本、元數(shù)據(jù)等,本文介紹了如何通過Python的pdfplumber庫提取pdf中表格數(shù)據(jù),感興趣的同學可以參考一下
    2023-05-05
  • python3調(diào)用c語言代碼的全過程記錄

    python3調(diào)用c語言代碼的全過程記錄

    python調(diào)用c語言代碼的方式十分簡單,只需四步。下面這篇文章就來給大家詳細介紹了關于python3如何調(diào)用c語言代碼的相關資料,需要的朋友可以參考下
    2021-05-05
  • Python使用py2exe打包程序介紹

    Python使用py2exe打包程序介紹

    這篇文章主要介紹了Python使用py2exe打包程序介紹,本文講解了py2exe簡介、安裝、用法、指定額外文件等內(nèi)容,需要的朋友可以參考下
    2014-11-11
  • Python實現(xiàn)Linux服務器自動巡檢腳本

    Python實現(xiàn)Linux服務器自動巡檢腳本

    這篇文章主要為大家介紹了一個使用Python語言實現(xiàn)的Linux服務器自動巡檢腳本,只需配置服務器ip、用戶名、密碼即可實現(xiàn)服務器自動巡檢,巡檢日志以txt文件輸出,免去了挨個敲命令巡檢的麻煩
    2025-06-06
  • Python警察與小偷的實現(xiàn)之一客戶端與服務端通信實例

    Python警察與小偷的實現(xiàn)之一客戶端與服務端通信實例

    這篇文章主要介紹了Python警察與小偷的實現(xiàn)之一客戶端與服務端通信實例,并附有難點及易錯點的分析與說明,需要的朋友可以參考下
    2014-10-10
  • python3 刪除所有自定義變量的操作

    python3 刪除所有自定義變量的操作

    這篇文章主要介紹了python3 刪除所有自定義變量的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • Python Scrapy多頁數(shù)據(jù)爬取實現(xiàn)過程解析

    Python Scrapy多頁數(shù)據(jù)爬取實現(xiàn)過程解析

    這篇文章主要介紹了Python Scrapy多頁數(shù)據(jù)爬取實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • python實現(xiàn)比較兩段文本不同之處的方法

    python實現(xiàn)比較兩段文本不同之處的方法

    這篇文章主要介紹了python實現(xiàn)比較兩段文本不同之處的方法,涉及Python針對文本與字符串的相關操作技巧,需要的朋友可以參考下
    2015-05-05
  • Numpy中np.max的用法及np.maximum區(qū)別

    Numpy中np.max的用法及np.maximum區(qū)別

    這篇文章主要介紹了Numpy中np.max的用法及np.maximum區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • python自動化測試selenium核心技術處理彈框

    python自動化測試selenium核心技術處理彈框

    這篇文章主要為大家介紹了python自動化測試selenium核心技術處理彈框的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-11-11

最新評論