简体   繁体   English

如何从 Docker 容器访问和运行主机上的命令?

[英]How to access and run command on host from Docker container?

I want to access my host bash from Docker container and run there netstat , then get result of netstat and render it with Python/Flask as HTML page.我想从 Docker 容器访问我的主机 bash 并在那里运行netstat ,然后获取 netstat 的结果并使用 Python/Flask 将其呈现为 HTML 页面。 Here is an example how i've done it without docker container.这是一个示例,我如何在没有 docker 容器的情况下完成它。

from flask import Flask, render_template

app = Flask(__name__)

def get_ports_data():
    import subprocess
    p = subprocess.Popen(['netstat', '-ltup'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    data = stdout.decode().split('\n')
    return data

@app.route('/')
def index():
    return render_template('index.html', portsdata=get_ports_data())

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')

It works great, but when i run it as a docker container i face a problem with accessing my host to run netstat and get a result.它工作得很好,但是当我将它作为 docker 容器运行时,我在访问我的主机以运行 netstat 并获得结果时遇到了问题。 How can i do this?我怎样才能做到这一点?

One of the benefits of Docker is that it isolates a process from the rest of the system, but that also means from inside the container it can be difficult to get information about the host operating system. Docker 的好处之一是它将进程与系统的 rest 隔离开来,但这也意味着从容器内部很难获取有关主机操作系统的信息。

I don't know your specific requirements, but my preferred solutions to this in order would be:我不知道您的具体要求,但我对此的首选解决方案是:

  1. Don't run this app inside a Docker container at all (its job seems to be gathering information about the host system, so isolating it from the host is counter-productive).根本不要在 Docker 容器中运行此应用程序(它的工作似乎是收集有关主机系统的信息,因此将其与主机隔离会适得其反)。

  2. Perhaps if you mount /proc/net as a read-only volume inside the container, you can read those files instead of executing netstat .也许如果您将/proc/net作为容器内的只读卷安装,您可以读取这些文件而不是执行netstat I don't know for sure if this would work and I'd be worried about the security implications, but it could be worth investigating.我不确定这是否可行,并且我会担心安全隐患,但这可能值得调查。

  3. Run a second service directly on the host which can execute netstat , and have this Flask app communicate with that service.直接在可以执行netstat的主机上运行第二个服务,并让这个 Flask 应用程序与该服务通信。

As stated in the docs , in order to run a command in a running container, you should:文档中所述,为了在正在运行的容器中运行命令,您应该:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

In your case, it should be something like:在你的情况下,它应该是这样的:

docker exec CONTAINER netstat -ltup

If you run如果你跑

docker exec -it CONTAINER bash

You'll execute an interactive Bash shell on the container.您将在容器上执行交互式 Bash shell。 If bash is not available, you can try sh instead.如果bash不可用,可以尝试sh代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM