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. Here is an example how i've done it without docker container.
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. 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.
I don't know your specific requirements, but my preferred solutions to this in order would be:
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).
Perhaps if you mount /proc/net
as a read-only volume inside the container, you can read those files instead of executing 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.
Run a second service directly on the host which can execute netstat
, and have this Flask app communicate with that service.
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. If bash
is not available, you can try sh
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.