[转] Docker中运行Python
参考链接: https://realpython.com/python-versions-docker/1年前 • 768次点击 • 来自 其他
原文链接:Run Python Versions in Docker: How to Try the Latest Python Release
本文将学习如何使用Docker运行Python,本文省略了对Docker的基础使用的介绍,作为在微服务领域大量使用的技术,请读者自行查阅相关文档。
使用Dockerfile构建ubuntu镜像
以下是Dockerfile的示例:
FROM ubuntu
RUN apt update && apt install -y cowsay
CMD ["/usr/games/cowsay", "Dockerfiles are cool!"]
Dockerfile由一系列Docker命令 commands组成。在上面的示例中,分三个步骤:
请将其保存在名为Dockerfile的文本文件中,且不带任何文件扩展名。
接下来,从您的Dockerfile构建镜像image:
$ docker build -t cowsay .
运行Docker image:
$ docker run --rm cowsay
_______________________
< Dockerfiles are cool! >
-----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
--rm
参数的意思是将在使用后清理您的容器。--rm
避免了使用陈旧的Docker容器填充系统。
在Docker容器中运行Python
要在Python容器中启动REPL,请运行以下命令:
$ docker run -it --rm python:rc
Python 3.8.0rc1 (default, Oct 2 2019, 23:30:03)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
该命令将从Docker Hub下载镜像python:rc
,启动一个容器,然后在该容器中运行python。-it
选项对于以交互方式运行容器是必需的。rc
标记是候选发行版的缩写,指向Python的最新开发版本。
输入一下代码:
>>> import sys
>>> f"{sys.version_info[:] = }"
"sys.version_info[:] = (3, 8, 0, 'candidate', 1)"
您可以像平常一样退出REPL,例如,输入exit()
。
设置您的Python环境
Docker容器是一个隔离的环境。因此,通常不需要在容器内添加虚拟环境。
以下示例将给一个Python 3.7.5
容器安装parse
与realpython-reader
:
FROM python:3.7.5-slim
RUN python -m pip install \
parse \
realpython-reader
保存文件Dockerfile,-slim
标签表示基于Debian的Python最小安装。该标签可以使Docker镜像体积小,但缺点是您可能需要自己安装更多其他工具。
要构建并运行您的Dockerfile,请使用以下命令:
$ docker build -t rp .
[ ... Output clipped ... ]
$ docker run -it --rm rp
输入代码检查parse是否安装成功:
>>> import parse
>>> parse.__version__
'1.12.1'
您还可以启动运行自定义命令的容器:
$ docker run --rm rp realpython
The latest tutorials from Real Python (https://realpython.com/)
0 Run Python Versions in Docker: How to Try the Latest Python Release
[ ... Full output clipped ... ]
无需启动REPL,而是在rp容器内运行realpython命令,该命令列出了在Real Python上发布的最新教程。
The latest tutorials from Real Python (https://realpython.com/)
0 The Real Python Podcast – Episode #47: Unraveling Python's Syntax to Its Core With Brett Cannon
1 Python Microservices With gRPC
2 Python Modulo: Using the % Operator
3 Python Inner Functions: What Are They Good For?
4 The Real Python Podcast – Episode #46: C for Python Developers and Data Visualization With Dash
5 Qt Designer and Python: Build Your GUI Applications Faster
6 Plot With Pandas: Python Data Visualization Basics
7 Python Web Applications: Deploy Your Script as a Flask App
8 The Real Python Podcast – Episode #45: Processing Images in Python With Pillow
9 Stochastic Gradient Descent Algorithm With Python and NumPy
10 Evaluate Expressions Dynamically With Python eval()
11 How to Use Python: Your First Steps
12 The Real Python Podcast – Episode #44: Creating an Interactive Online Python Conference for PyCascades 2021
13 C for Python Programmers
14 Introduction to Sorting Algorithms in Python
15 Make Your First Python Game: Rock, Paper, Scissors!
16 The Real Python Podcast – Episode #43: Deep Reinforcement Learning in a Notebook With Jupylet + Gaming and Synthesis
17 Sentiment Analysis: First Steps With Python's NLTK Library
18 Managing Python Dependencies
19 NumPy Tutorial: Your First Steps Into Data Science in Python
20 The Real Python Podcast – Episode #42: What Is Data Engineering and Researching 10 Million Jupyter Notebooks
21 Building HTTP APIs With Django REST Framework
22 Django Admin Customization
23 The Real Python Podcast – Episode #41: 2020 Real Python Articles in Review
24 Serializing Objects With the Python pickle Module
25 The Real Python Podcast – Episode #40: How Python Manages Memory and Creating Arrays With np.linspace
26 Python Turtle for Beginners
27 The Real Python Podcast – Episode #39: Generators, Coroutines, and Learning Python Through Exercises
28 Speed Up Python With Concurrency
29 The Real Python Podcast – Episode #38: Looping With enumerate() and Python GUIs With PyQt
使用Docker运行Python脚本
在本节中,您将看到如何在Docker中运行脚本。首先,将以下示例脚本保存/home/realpython/code
目录下,并命名为headlines.py
:
# headlines.py
import parse
from reader import feed
print("Start to get all headlines:")
tutorial = feed.get_article(0)
headlines = [
r.named["header"]
for r in parse.findall("\n## {header}\n", tutorial)
]
print("\n".join(headlines))
该脚本首先从Real Python下载最新的教程。然后,它使用parse查找教程中的所有标题,并将其打印到控制台。
在Docker容器中有两种运行脚本的方法:
- 将本地目录作为卷 volume 挂载在Docker容器中。
- 将脚本复制到Docker容器中。
第一个选项在测试期间特别有用,因为在更改脚本时不需要重建Docker镜像。要将目录挂载为卷,请使用以下-v
选项:
$ docker run --rm -v /home/realpython/code:/app rp python /app/headlines.py
如果要将脚本部署到另一台计算机,则需要将脚本复制到容器中。为此,您需要在Dockerfile中添加一些步骤:
FROM python:3.7.5-slim
WORKDIR /usr/src/app
RUN python -m pip install \
parse \
realpython-reader
COPY headlines.py .
CMD ["python", "headlines.py"]
您可以在容器内设置一个工作目录来控制命令的运行位置。然后将headlines.py
复制到容器中的该工作目录,并更改默认命令以使用python运行headlines.py。重建镜像,然后运行容器:
$ docker build -t rp .
[ ... Output clipped ... ]
$ docker run --rm rp
Understanding Python Versions and Docker
Using Docker
Running Python in a Docker Container
Conclusion
Further Reading