日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

利用Docker?運行?python?簡單程序_docker

作者:小公雞卡哇伊呀~ ? 更新時間: 2022-06-22 編程語言

以下是一個簡單的 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>?

原文鏈接:https://blog.csdn.net/ftell/article/details/124366209

欄目分類
最近更新