如何访问Docker容器内运行的Bokeh Server?求可运行示例
解决Docker中Dash集成Bokeh Server的访问问题
问题背景
本地环境下,Dash应用调用Bokeh Server可正常通过http://localhost:5006/simple_bokeh_example访问图表,但构建Docker镜像后,Bokeh Server虽启动却无法访问——核心原因是容器内的localhost指向容器自身而非主机,且原代码未正确配置Bokeh的监听地址、Docker端口映射也不完整。
修改后的完整可运行示例
1. Dash应用代码(bokeh_test.py)
import dash from dash import html from dash.dependencies import Input, Output import subprocess app = dash.Dash(__name__) app.layout = html.Div([ html.Button("启动Bokeh示例", id="open-bokeh-button"), html.Div(id="output") ]) @app.callback( Output("output", "children"), Input("open-bokeh-button", "n_clicks") ) def start_bokeh_example(n_clicks): if n_clicks is not None and n_clicks > 0: try: # 后台启动Bokeh Server,绑定所有接口和指定端口 subprocess.Popen( ["bokeh", "serve", "--host", "0.0.0.0:5006", "--port", "5006", "simple_bokeh_example.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # 返回可访问的链接(主机访问用localhost:5006) return html.Div([ html.P("Bokeh Server已启动"), html.A("点击访问Bokeh图表", href="http://localhost:5006/simple_bokeh_example", target="_blank") ]) except Exception as e: return html.Div([f"启动失败: {str(e)}"]) return "" if __name__ == "__main__": app.run_server(debug=True, host="0.0.0.0", port=8050)
2. Bokeh示例代码(simple_bokeh_example.py)
无需修改,保持原代码即可:
from random import random from bokeh.layouts import column from bokeh.models import Button from bokeh.palettes import RdYlBu3 from bokeh.plotting import figure, curdoc p = figure(x_range=(0, 100), y_range=(0, 100), toolbar_location=None) p.border_fill_color = 'black' p.background_fill_color = 'black' p.outline_line_color = None p.grid.grid_line_color = None r = p.text(x=[], y=[], text=[], text_color=[], text_font_size="26px", text_baseline="middle", text_align="center") i = 0 ds = r.data_source def callback(): global i new_data = dict() new_data['x'] = ds.data['x'] + [random() * 70 + 15] new_data['y'] = ds.data['y'] + [random() * 70 + 15] new_data['text_color'] = ds.data['text_color'] + [RdYlBu3[i % 3]] new_data['text'] = ds.data['text'] + [str(i)] ds.data = new_data i = i + 1 button = Button(label="Press Me") button.on_event('button_click', callback) curdoc().add_root(column(button, p))
3. Dockerfile
FROM python:3.9-slim WORKDIR /app COPY . /app # 安装依赖,确保包含dash和bokeh RUN pip install --no-cache-dir dash bokeh # 暴露Dash的8050端口和Bokeh的5006端口 EXPOSE 8050 5006 CMD ["python", "bokeh_test.py"]
4. 运行步骤
- 构建Docker镜像:
docker build -t dash-bokeh-app .
- 启动容器(映射主机端口到容器端口):
docker run -p 8050:8050 -p 5006:5006 dash-bokeh-app
- 访问Dash应用:打开浏览器访问
http://localhost:8050,点击按钮启动Bokeh Server,再点击链接访问图表。
关键修改说明
- Bokeh Server配置:添加
--host 0.0.0.0:5006让服务监听容器内所有网络接口,避免仅监听容器内部localhost;用subprocess.Popen后台启动,防止阻塞Dash回调。 - Docker端口映射:同时映射8050(Dash)和5006(Bokeh)端口,确保主机能访问容器内的两个服务。
- 访问链接提供:在Dash回调返回中直接给出可访问的URL,简化用户操作。
内容的提问来源于stack exchange,提问作者xfactor
相关产品推荐
相关产品推荐

