將Python Flask服務(wù)打包成Docker鏡像并運(yùn)行的完整指南
前言
在現(xiàn)代軟件開(kāi)發(fā)中,容器化技術(shù)已經(jīng)成為部署應(yīng)用程序的標(biāo)準(zhǔn)方式之一。Docker作為最流行的容器化平臺(tái),能夠幫助開(kāi)發(fā)者輕松打包、分發(fā)和運(yùn)行應(yīng)用程序。本文將詳細(xì)介紹如何將一個(gè)簡(jiǎn)單的Python Flask服務(wù)打包成Docker鏡像并運(yùn)行。
準(zhǔn)備工作
在開(kāi)始之前,請(qǐng)確保你的系統(tǒng)已經(jīng)安裝了以下工具:
1.Docker(官方安裝指南)
2.Python 3.x(可選,用于本地測(cè)試)
項(xiàng)目結(jié)構(gòu)
我們的項(xiàng)目包含以下文件:
. ├── Dockerfile ├── .dockerignore ├── requirements.txt └── wisdom_app.py
具體步驟
1. 創(chuàng)建Python Flask應(yīng)用
首先,我們有一個(gè)簡(jiǎn)單的Flask應(yīng)用wisdom_app.py,它會(huì)隨機(jī)顯示編程名言和有趣的圖片。
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"}
]
# 有趣的動(dòng)物圖片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)
# 簡(jiǎn)單的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="有趣的動(dòng)物">
</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__':
# 獲取端口號(hào),默認(rèn)為5000
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
2. 創(chuàng)建requirements.txt
列出項(xiàng)目所需的Python依賴(lài):
flask==2.3.2 importlib-metadata>=3.6.0 Werkzeug==2.3.7
3. 編寫(xiě)Dockerfile(注意文件名沒(méi)有后綴)
Dockerfile是構(gòu)建鏡像的核心文件,我們使用多階段構(gòu)建來(lái)優(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)依賴(lài)(先清理緩存再更新)
RUN apt-get clean && \
apt-get update && \
apt-get install -y --no-install-recommends build-essential && \
rm -rf /var/lib/apt/lists/*
# 升級(jí) pip 并安裝依賴(lài)
RUN pip install --upgrade pip setuptools wheel && \
pip install importlib-metadata>=3.6.0
# 復(fù)制并安裝 Python 依賴(lài)(使用阿里云 PyPI 源加速)
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt
# 最終運(yùn)行鏡像
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
# 安裝運(yùn)行時(shí)依賴(lài)
RUN apt-get clean && \
apt-get update && \
apt-get install -y --no-install-recommends libgomp1 && \
rm -rf /var/lib/apt/lists/*
# 復(fù)制構(gòu)建產(chǎn)物和應(yīng)用代碼
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.9/site-packages/ /usr/local/lib/python3.9/site-packages/
COPY wisdom_app.py .
# 暴露端口并啟動(dòng)應(yīng)用
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. 構(gòu)建Docker鏡像
打開(kāi)cmd,cd到項(xiàng)目目錄,執(zhí)行以下命令構(gòu)建鏡像:
docker build -t wisdom-app:latest .
參數(shù)說(shuō)明:
-t wisdom-app:latest :為鏡像指定名稱(chēng)和標(biāo)簽 . :使用當(dāng)前目錄中的Dockerfile
6. 運(yùn)行Docker容器
構(gòu)建完成后,可以使用以下命令運(yùn)行容器:
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ù)說(shuō)明:
-it:以交互模式運(yùn)行容器 -p 5000:5000:將容器的5000端口映射到主機(jī)的5000端口 --host=0.0.0.0:允許外部訪(fǎng)問(wèn)Flask應(yīng)用
7. 測(cè)試應(yīng)用
在瀏覽器中訪(fǎng)問(wèn)http://localhost:5000,你應(yīng)該能看到隨機(jī)顯示的名言和圖片。

8. 其他有用的Docker命令
查看運(yùn)行中的容器:
docker ps
停止容器:
docker stop <容器ID>
刪除容器:
docker rm <容器ID>
刪除鏡像:
docker rmi wisdom-app:latest
進(jìn)入運(yùn)行中的容器:
docker exec -it <容器ID> /bin/bash
常見(jiàn)問(wèn)題解決
端口沖突:如果5000端口已被占用,可以修改映射端口,如-p 5001:5000
構(gòu)建緩慢:確保使用了國(guó)內(nèi)鏡像源(如阿里云),如Dockerfile中所示
容器立即退出:檢查應(yīng)用是否有錯(cuò)誤日志,使用docker logs <容器ID>查看
無(wú)法訪(fǎng)問(wèn)應(yīng)用:確保容器正確運(yùn)行,并且防火墻允許對(duì)應(yīng)端口的訪(fǎng)問(wèn)
以上就是將Python Flask服務(wù)打包成Docker鏡像并運(yùn)行的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python Flask打包成Docker鏡像的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python利用pdfplumber庫(kù)提取pdf中表格數(shù)據(jù)
pdfplumber是一個(gè)用于從PDF文檔中提取文本和表格數(shù)據(jù)的Python庫(kù),它可以幫助用戶(hù)輕松地從PDF文件中提取有用的信息,例如表格、文本、元數(shù)據(jù)等,本文介紹了如何通過(guò)Python的pdfplumber庫(kù)提取pdf中表格數(shù)據(jù),感興趣的同學(xué)可以參考一下2023-05-05
python3調(diào)用c語(yǔ)言代碼的全過(guò)程記錄
python調(diào)用c語(yǔ)言代碼的方式十分簡(jiǎn)單,只需四步。下面這篇文章就來(lái)給大家詳細(xì)介紹了關(guān)于python3如何調(diào)用c語(yǔ)言代碼的相關(guān)資料,需要的朋友可以參考下2021-05-05
Python實(shí)現(xiàn)Linux服務(wù)器自動(dòng)巡檢腳本
這篇文章主要為大家介紹了一個(gè)使用Python語(yǔ)言實(shí)現(xiàn)的Linux服務(wù)器自動(dòng)巡檢腳本,只需配置服務(wù)器ip、用戶(hù)名、密碼即可實(shí)現(xiàn)服務(wù)器自動(dòng)巡檢,巡檢日志以txt文件輸出,免去了挨個(gè)敲命令巡檢的麻煩2025-06-06
Python警察與小偷的實(shí)現(xiàn)之一客戶(hù)端與服務(wù)端通信實(shí)例
這篇文章主要介紹了Python警察與小偷的實(shí)現(xiàn)之一客戶(hù)端與服務(wù)端通信實(shí)例,并附有難點(diǎn)及易錯(cuò)點(diǎn)的分析與說(shuō)明,需要的朋友可以參考下2014-10-10
Python Scrapy多頁(yè)數(shù)據(jù)爬取實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Python Scrapy多頁(yè)數(shù)據(jù)爬取實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
python實(shí)現(xiàn)比較兩段文本不同之處的方法
這篇文章主要介紹了python實(shí)現(xiàn)比較兩段文本不同之處的方法,涉及Python針對(duì)文本與字符串的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05
Numpy中np.max的用法及np.maximum區(qū)別
這篇文章主要介紹了Numpy中np.max的用法及np.maximum區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
python自動(dòng)化測(cè)試selenium核心技術(shù)處理彈框
這篇文章主要為大家介紹了python自動(dòng)化測(cè)試selenium核心技術(shù)處理彈框的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11

