我有一个 docker 镜像和相关的容器,并运行 jupyter-lab 服务器。在这个 docker 镜像上,我有一个无法安装在主机上的非常具体的 python 模块。在我的主机上,我有我不想在 docker 容器上运行的所有工作环境。
我想使用在主机上运行的 python 脚本中的那个模块。我的第一个想法是像这样在主机上使用 docker-py
(https://github.com/docker/docker-py):
import docker
client = docker.from_env()
container = client.container.run("myImage", detach=True)
container.exec_run("python -c 'import mymodule; # do stuff; print(something)'")
并获取输出并继续在我的脚本中工作。
有更好的解决方案吗?例如,有没有办法在主机上的脚本中连接到 jupyter 服务器?
谢谢
答案 0 :(得分:0)
首先。正如@dagnic states 在他的评论中所说,有 2 个模块可让您在 Python 脚本中执行 docker 运行时(可能还有更多,另一个不同的问题是“哪个是最好的”)。
第二。对 Jupiter 一无所知,但既然你称它为“服务器”,那对我来说就意味着你可以port mapping那个服务器(记住 -p 8080:80 或 --publish 8080:80,是的,就是这样!)。为您的容器设置端口映射后,您就可以使用 pycurl 模块与该服务进行“对话”。
请记住,如果您与服务器“通过端口进行通信”,您可能还想使用 docker-py 来执行此操作。
既然你问是否存在更好的解决方案:这两种方法会更受欢迎。第一个对你的脚本很方便,第二个会启动一个服务器,你可以按照你的要求从你的主机脚本中使用 pycurl(连接到 jupyter 服务器)。即,如果你启动 jupyter 服务器,如:
docker run -p 9999:8888 -it -e JUPYTER_ENABLE_LAB=yes jupyter/base-notebook:latest
你可以像这样:
import pycurl
from io import BytesIO
b_obj = BytesIO()
crl = pycurl.Curl()
# Set URL value
crl.setopt(crl.URL, 'https://localhost:8888')
# Write bytes that are utf-8 encoded
crl.setopt(crl.WRITEDATA, b_obj)
# Perform a file transfer
crl.perform()
# End curl session
crl.close()
# Get the content stored in the BytesIO object (in byte characters)
get_body = b_obj.getvalue()
# Decode the bytes stored in get_body to HTML and print the result
print('Output of GET request:\n%s' % get_body.decode('utf8'))
更新:
所以你有两个问题:
1.有没有更好的解决方案? 基本上使用 docker-py 模块并在 docker 容器中运行 jupyter 服务器(以及我认为不涉及 docker 的其他一些选项)
2.例如,有没有办法在主机上的脚本中连接到 jupyter 服务器?
这里有一个如何在 docker 中运行 jupyter 的例子。 enter link description here
剩下的就是使用代码中的 pycurl 与主机上的 jupyther 服务器通信。