使用 Docker 运行简单的 python 程序

以下是一个简单的 python 程序,用户输入一个最小值和最大值,输出二者之间的随机数:

from random import randint

min_number = int(input('Please enter the min number: '))
max_number = int(input('Please enter the max number: '))

if (max_number < min_number): 
  print('Invalid input - shutting down...')
else:
  rnd_number = randint(min_number, max_number)
  print(rnd_number)

本机上并未安装 python, 现在创建容器,并让这段代码在容器中运行:

1. 首先写一个 Dockerfile:

# 从 hub.docker.com 上 pull 最新 python image
FROM python

# 容器内的工作目录
WORKDIR /app

# copy 源代码到容器
COPY . /app

CMD ["python", "rng.py"]

在这里插入图片描述

2. build image,使用命令:

docker build .

3. 创建并运行容器:

对于这个程序,直接运行: docker run he_generated_id_of_the_image 会出错:

docker run the_generated_id_of_the_image // ERROR !

而是要在命令中加 -it :
-it-i-t 的合并。
-i: interactive 与容器交互
-t: tty 分配一个伪 TTY, 即创建一个终端。

docker run -it the_generated_id_of_the_image

用户可以在容器内输入数据,并获得输出:

PS D:\python-app-starting-setup> docker run -it 7e318e98ef5c
Please enter the min number: 12
Please enter the max number: 24
22
PS D:\python-app-starting-setup> 

4. 重启容器,

docker run 重新生成新的容器,默认模式为 attached 即附加模式,使用附加模式时,容器在前台运行,可以监听该容器的输出,同时终端被阻塞,无法响应用户的新的输入命令。

docker start 则重启运行现有的容器, 默认模式为 detached 即分离模式,容器在后台运行。

如果应用程序,依赖项,以及源代码等等都没有改变,也就是 image 没有变,那么没有必要创建全新的容器,而是直接用 docker start 重新启动现有的容器就可以。

使用 docker ps -a 或者 docker container ls -a 列出全部正在运行以及已经停止的容器:

CONTAINER ID   IMAGE          COMMAND                  CREATED             STATUS                         PORTS     NAMES
4082f25c47bb   7e318e98ef5c   "python rng.py"          4 minutes ago       Exited (0) 4 minutes ago                 jovial_pasteur
ce7598ddbebb   7e318e98ef5c   "python rng.py"          About an hour ago   Exited (1) About an hour ago             nostalgic_cohen
df76886dc1a4   7e318e98ef5c   "python rng.py"          About an hour ago   Exited (0) About an hour ago             clever_hertz
71b61835bfb3   python         "python3"                2 hours ago         Exited (0) 2 hours ago                   hardcore_payne
89211c5ce6cd   834a8f2178cf   "docker-entrypoint.s…"   3 hours ago         Exited (137) 2 hours ago                 goofy_sinoussi

现在重启容器,重新执行 python 程序,使用命令:

 docker start -a -i 4082f25c47bb

-t 不需要,因为已经被 memorized,运行结果:

PS D:\python-app-starting-setup>  docker start -a -i 4082f25c47bb
Please enter the min number: 1
Please enter the max number: 100
44
PS D:\udemy\Docker-Max\python-app-starting-setup> 
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值