首页 > 解决方案 > 如何在一个命令中运行容器并在 docker 上执行 python?

问题描述

我们有一个非常小的 Python 代码,需要在容器上运行。以下两个命令工作正常,我想将它们合并为一个?最终目标是容器应该启动(基于图像),运行python并自行退出。

docker run --name mycontainer -v /opt/testuser/pythoncode/:/usr/src/app/ -t -d pythonimage:latest
docker exec -it mycontainer python3 /usr/src/app/subfolder/createfile.py

我试过 -c "/bin/bash python3 /usr/src/app/subfolder/createfile.py" 这没用,它只是。

标签: pythondockercontainers

解决方案


您可以添加一个名为Dockerfile(文件名前后没有点,正是这个)的文件,其内容如下:

from ubuntu:20.04
env run=/usr/src/app/subfolder/createfile.py
cmd ["/bin/bash", "-c", "${run}"]

然后运行:

docker build YOUR_IMAGE_NAME # this should be a new name, like pythonimage2

现在运行它:

docker run --name mycontainer -v /opt/testuser/pythoncode/:/usr/src/app/ -t -d pythonimage2:latest

所以,现在让容器运行的 docker 执行命令是 now /usr/src/app/subfolder/createfile.py

关于您的答案,您可以添加一个变量,每次只需修改该行。

即使您可以对您的Dockerfile:

from ubuntu:20.04
env path=/usr/src/app/subfolder/
env file=$path/createfile.py
cmd ["/bin/bash", "-c", "${file}"]

现在你只需要修改file变量。如果您的任何子目录发生更改,您可以将其从path变量中删除并将其添加到file变量中。


推荐阅读