Docker による Voilà アプリの公開

2023年8月21日

はじめに

Docker を用いて Voilà アプリを公開することを考える。作業は Ubuntu で行う。

Docker イメージの作成

作業ディレクトリを作成する。

$ mkdir voila
$ cd voila

公開するノートブックを用意する (コード部分のみ)。

sqrt.ipynb

import ipywidgets as widgets
from IPython.display import display

answer = widgets.Label(value="")
text = widgets.Text(value="",
            placeholder="数値を入力",
            description="数値:",
            disabled=False
           )

def sqrt(a):
    if a <= 0: return 0
    x = 1.
    for i in range(10):
        x = x - (x**2 - a)/(2.*x)
    return x

def handle_text_change(change):
    try:
        a = float(change.new)
        x = sqrt(a)
        answer.value = str(x)
    except:
        pass

text.observe(handle_text_change, names="value")

display(text)
display(answer)

Dockerfile は以下のようになる。

Dockerfile

FROM python:3.9-slim

RUN pip install jupyter matplotlib numpy scipy pandas ipywidgets ipympl voila

WORKDIR /app
ADD ./sqrt.ipynb /app

EXPOSE 8866
ENTRYPOINT ["voila", "sqrt.ipynb", "--port=8866", "--no-browser", "--Voila.ip=0.0.0.0"]

ビルド。

$ docker build -t voila .
$ docker images
REPOSITORY     TAG       IMAGE ID       CREATED          SIZE
voila          latest    6457f52cf374   54 minutes ago   793MB

実行。

$ docker run -p 8866:8866 voila
[Voila] Using /tmp to store connection files
[Voila] Storing connection files in /tmp/voila_we6_jc0d.
[Voila] Serving static files from /usr/local/lib/python3.9/site-packages/voila/static.
[Voila] Voilà is running at:
http://fce5f3447c58:8866/

http://localhost:8866/ にブラウザでアクセスする。