如何把Python应用构建为Docker容器

【开发工具|Docker】—— 如何用 Docker 快速部署 Python 项目 Docker 是一个开源平台,用于自动化应用程序的部署、扩展和管理。它通过容器技术实现轻量级、可移植的应用打包,确保在不同环境中应用的一致性。本文使用docker简单演示了如何部署一个python项目。 阅读详情

现在云原生越来越流行, 容器化势在必行, 作为一个开发人员, 多多少少也要接触一些容器相关的操作, 其中最基础的操作是如何把自己的应用构建为一个 Docker 容器, 并管理。本文以 starlette 框架和后台的开发常见3件套 Nginx , MySQL 和 Redis 为底创建一个简单的Web后台演示项目, 并一步一步介绍如何编写成一个容器以及容器的运行。

1.创建项目

第一步会先创建一个 Python 后台项目, 这个项目包含3个接口, 一个接口用来测试服务是否正常, 另外一个是测试 MySQL 调用, 最后一个是测试 Redis 调用。

首先是创建一个后台项目以及依赖:

➜  example_python git:(master) mkdir python_on_docker          
➜  example_python git:(master) cd python_on_docker 
# 一个项目配套一个虚拟环境, 如果熟悉, 建议用porety来处理项目的python和venv配套环境问题, 这里为了演示方便, 使用了venv
➜  python_on_docker git:(master) python3.7 -m venv venv
➜  python_on_docker git:(master) source venv/bin/activate 
➜  python_on_docker git:(master) touch __init__.py  # 每个Python项目要确保有一个__init__.py文件 

# 可以看到多了个venv的环境, 目前已经切到venv, 开始安装依赖
(venv) ➜  python_on_docker git:(master) pip install starlette aiomysql aioredis uvicorn
(venv) ➜  python_on_docker git:(master) pip install cryptography  # aiomysql需要该模块提供加密算法
# 生成pip安装的依赖文件
(venv) ➜  python_on_docker git:(master) python -m pip freeze > requirements.txt

之后创建项目主文件 example.py , 该文件主要提供API服务,里面包含上面所说的3个接口, 示例代码如下(源码):

from typing import Optional, Tuple

import aiomysql
import aioredis
from starlette.applications import Starlette
from starlette.config import Config
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route


config: Config = Config(".env")
mysql_pool: Optional[aiomysql.Pool] = None
redis: Optional[aioredis.Redis] = None


async def on_start_up():
    """连接MySQL和Redis"""
    global mysql_pool
    global redis

    mysql_pool = await aiomysql.create_pool(
        host=config("MYSQL_HOST"),
        port=config("MYSQL_PORT", cast=int),
        user=config("MYSQL_USER"),
        password=config("MYSQL_PW"),
        db=config("MYSQL_DB"),
    )
    redis = aioredis.Redis(
        await aioredis.create_redis_pool(
            config("REDIS_URL"),
            minsize=config("REDIS_POOL_MINSIZE", cast=int),
            maxsize=config("REDIS_POOL_MAXSIZE", cast=int),
            encoding=config("REDIS_ENCODING")
        )
    )


async def on_shutdown():
    """关闭MySQL和Redis连接"""
    await mysql_pool.wait_closed()
    await redis.wait_closed()


def hello_word(request: Request) -> PlainTextResponse:
    """测试接口调用接口"""
    return PlainTextResponse("Hello Word!")


async def mysql_demo(request: Request) -> JSONResponse:
    """测试MySQL调用接口"""
    count: int = int(request.query_params.get("count", "0"))
    async with mysql_pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT %s;", (count, ))
            mysql_result_tuple: Tuple[int] = await cur.fetchone()
    return JSONResponse({"result": mysql_result_tuple})


async def redis_demo(request: Request) -> JSONResponse:
    """测试Redis调用接口"""
    count: int = int(request.query_params.get("count", "0"))
    key: str = request.query_params.get("key")
    if not key:
        return JSONResponse("key is empty")
    result: int = await redis.incrby(key, count)
    await redis.expire(key, 60)
    return JSONResponse({"count": result})


app: Starlette = Starlette(
    routes=[
        Route('/', hello_word),
        Route('/mysql', mysql_demo),
        Route('/redis', redis_demo)
    ],
    on_startup=[on_start_up],
    on_shutdown=[on_shutdown]
)

项目文件创建完毕, 接着再创建一个配套的配置文件 .env ( starlette 的config会自动加载 .env 的配置):

# 按自己的配置信息更改配置
MYSQL_DB="mysql"
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"
MYSQL_USER="root"
MYSQL_PW=""

REDIS_URL="redis://localhost"
REDIS_POOL_MINSIZE=1
REDIS_POOL_MAXSIZE=10
REDIS_ENCODING="utf-8"

到现在为止, 目录里只有 example.py 主文件, .env 配置文件以及 requirements.txt 的依赖文件, 现在开始启动应用查看应用是否能正常启动(注意修改mysql和redis的配置文件, 目前假设已经在本地安装好mysql和redis):

# 使用python -m uvicorn可以防止调用到外部的uvicorn
python -m uvicorn example:app
# 以下为终端输出
INFO:     Started server process [4616]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

通过终端的输出可以看到我们的服务已经启动并监听本机的8000端口,接下来测试接口可否正常使用:

➜  curl http://127.0.0.1:8000
Hello Word!
➜  curl http://127.0.0.1:8000/mysql
{"result":[0]}
➜  curl http://127.0.0.1:8000/mysql\?count\=10
{"result":[10]}
➜  curl http://127.0.0.1:8000/mysql\?count\=50
{"result":[50]}
➜  curl http://127.0.0.1:8000/redis\?key\=test
{"count":0}
➜  curl http://127.0.0.1:8000/redis\?key\=test\&count\=2
{"count":2}
➜  curl http://127.0.0.1:8000/redis\?key\=test\&count\=2
{"count":4}
➜  curl http://127.0.0.1:8000/redis\?key\=test\&count\=2
{"count":6}
➜  curl http://127.0.0.1:8000/redis\?key\=test\&count\=2
{"count":8}    

通过输出可以发现, 我们的测试结果正常, 接口可以正常使用,前菜到此结束, 接下来是开始利用 Docker 部署Python Web应用之旅.

2.为项目创建镜像并运行

目前我们还没碰过 Docker , 从这里开始, 就开始使用 Docker 了, 但在使用之前要确保自己安装了 Docker , 每个平台都有不同的安装方法且资料很多, 官方资料也很详细, 这里就不多做描述了。

在 Docker 中创建镜像很简单, 只需要通过一个 Dockerfile 文件来告诉 Docker 如何制作镜像即可, Dockerfile 主要包括两个用途, 一个是对当前镜像的描述;一个是指导 Docker 完成应用的容器化(创建一个包含当前应用的镜像), Dockerfile 能实现开发和部署两个过程的无缝切换, 同时 Dockerfile 还能帮助新手快速熟悉这个项目( Dockerfile 对当前的应用及其依赖有一个清晰准确的描述,并且非常容易阅读和理解,因此,要像重视你的代码一样重视这个文件,并且将它纳入到源控制系统当中.

简单的了解后开始编写对应的 Dockerfile 文件, 文件如下(源码):

# 拉取python的基础镜像, 具体使用python -V查看刚才自己是哪个版本的
FROM python:3.7.4-alpine
# 设置当前镜像的维护者
LABEL maintainer="so1nxxxx@gmail.com"
# 设置工作目录
WORKDIR /data/app
# 复制本地依赖, 每个COPY会新建一个镜像层
COPY . .

# 设置环境变量
#
python项目 以docker形式打包部署全流程 在很久很久以前,我已经听过Docker的大名,当时服务着急上线虽然考虑过用Docker来部署我的服务,但是因为赶期的原因放弃了。这两天因为华为云服务器到期,而且阿里云服务器优惠力度特别大的原因,我要把华为云服务器里的工程迁移到阿里云。迁移的过程中,大量的时间精力浪费在了重装python,加载依赖,迁移项目,配置端口等环境配置的工作上。我在想,如果当时用了Docker部署,我至于受这气?于是,一不做二不休,就花了点时间把部署以docker的形式部署了。 阅读详情

相关推荐

Docker化Python应用:轻松构建、部署与优化的容器化之旅

在当今快速发展的软件开发领域,容器化技术如Docker已成为提升开发、部署效率的重要工具。Docker为Python应用提供了一种轻量级、可移植的运行环境,确保应用在不同环境中的一致性。本文将详细介绍如何将Python应用与Docker结合使用,包括创建Dockerfile、构建镜像、运行容器等步骤,并探讨容器化对持续集成/持续部署(CI/CD)流程的积极影响。

liuxin33445566的博客 737

【Docker项目实战】在Docker下部署python测试环境

【Docker实战】在Docker下部署python测试环境

jks212454的博客 1807

程序化广告行业(23/89):深度剖析广告效果评估指标

大家好,我一直希望能和大家一起在技术领域不断探索、共同进步。在之前的文章中,我们了解了程序化广告中腾讯的业务布局和广告效果评估的基础概念,今天让我们进一步深入剖析广告效果评估的各项指标,这对理解程序化广告的运作机制至关重要

yyy173611的博客 4872

ROS激光雷达动态避障算法优化(C++实战)

本文深入探讨了ROS激光雷达动态避障算法的C++实战优化。针对动态环境的核心挑战,文章系统性地介绍了从激光数据预处理(降噪、瘦身)、动态障碍物检测与跟踪,到基于动态窗口法(DWA)的智能决策与调优的全流程。重点分享了如何将障碍物速度预测融入DWA打分函数,以实现更安全、流畅的避障,并提供了工程架构、性能优化及真机调试的实用建议。

weixin_29192141的博客 950

【智能优化算法】2024年SCI鳗鱼-石斑鱼优化算法(EGO),含MathType公式、word伪代码、visio流程图、matlab代码等。

该文中包括5个内容:用MathType编辑的公式、伪代码、visio的流程图,matlab代码,PDF论文,拿来直接用,可以帮助科研者省下超多时间。 鳗鱼-石斑鱼优化算法(Eel and grouper optimizer ,EGO)是一种新型的元启发式算法(智能优化算法),灵感来源于海洋生态系统中鳗鱼和石斑鱼的共生作用和觅食策略。该成果由Ali Mohammadzadeh和Seyedali Mirjalili两位作者于2024年6月发表在SCI著名期刊《Cluster Computing》上。

2301_79359347的博客 1046

PYTHON 打印三角形大全

用PYTHON语言打印各种三角形

世上无难事,只要肯攀登 1万+

基于DNN、CNN与SVM的串联电弧故障智能检测:从原理到嵌入式部署

在电气安全与工业物联网领域,时间序列分类是处理传感器信号、实现状态监测与故障诊断的核心技术。其原理在于从连续的信号数据中提取有效特征,并利用机器学习模型识别异常模式。这项技术的核心价值在于能够实现设备预测性维护、提升系统安全性并降低运维成本,广泛应用于智能电表、电机健康监测、电力设备保护等场景。本文聚焦于电气安全中的一个具体且危险的隐患——串联电弧故障的检测。针对这一隐蔽性强、传统方法误报率高的问题,项目深入实践了三种主流AI模型:深度神经网络、卷积神经网络和支持向量机。通过对比DNN的通用特征学习能力、C

weixin_31860973的博客 417

Visual Studio 6.0 镜像下载全指南:从企业版到中文版

本文提供Visual Studio 6.0企业版和中文版的镜像下载全指南,包括详细版本解析、已验证的下载链接及校验信息。针对现代系统的安装技巧和兼容性处理方案,帮助开发者高效获取并运行这一经典开发工具,特别适合维护遗留系统的专业人员。

weixin_33712987的博客 1214

python cartopy绘制扇形区域图/cartopy绘制北极部分区域

实际上,这个问题原因还是由于投影转换的问题,在set_extend时,绘制的上下边界仍然是方形、未被正确投影的边界,与我们的set_boundary存在冲突,最根本的原因还是在于cartopy对于投影计算的一些缺陷。另外我们需要指出的是:**该方法不适用于极地投影,即NorthPolarStereo,由于NorthPolarStereo本身投影特性只需一个参数,本身并不适合。我们绘制极地投影时,同样也是使用set_boundary绘制圆形边界,那么当我们想要绘制扇形时,可以通过。请根据喜好自行选择,

weixin_43750300的博客 3213

081、LLC谐振变换器的短路特性与保护

本文深入分析了LLC谐振变换器在短路工况下的特性与保护策略。作者通过实际案例指出,LLC在输出短路时会出现谐振电流失控、ZVS条件丧失等危险现象,导致MOS管炸毁。文章详细阐述了短路保护的三大难点:响应速度、频率与电流的耦合、重启策略,并提出了硬件级快速保护、频率快速拉升、打嗝模式等实用解决方案。作者分享了关键参数设计经验,包括电流检测阈值设置、最高频率限制和保护响应时间控制,并通过实测波形验证了保护效果。最后总结出五点重要经验,强调硬件保护的必要性和系统设计的注意事项,为LLC变换器的短路保护设计提供了有

Jack010169的博客 83

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

上一篇: Node.js 对比 Python:优点、缺点和用例
下一篇: python自带性能强悍的标准库 itertools
Python_xiaowu
博客等级 码龄5年 3096粉丝 178原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址