Skip to content

Instantly share code, notes, and snippets.

@jaman
Created March 25, 2024 14:13
Show Gist options
  • Save jaman/c88fbdfdf923cca500ed6a29a434e79c to your computer and use it in GitHub Desktop.
Save jaman/c88fbdfdf923cca500ed6a29a434e79c to your computer and use it in GitHub Desktop.
Quickly getting livebook to host a liveview server in a docker container.

LIveViewPlayground in Docker

Mix.install([
  {:liveview_playground, "~> 0.1.1"}
])

Section

defmodule LVP do
  @moduledoc """
  Documentation for `LVP`.
  Quick hack to serve via livebook hosted in docker.
  Accept connections from other hosts to the internal port.
  """
  def start(opts \\ []) do
    router = Keyword.get(opts, :router, LiveviewPlayground.Router)
    endpoint = Keyword.get(opts, :endpoint, LiveviewPlayground.Endpoint)
    ip = Keyword.get(opts, :ip, {127, 0, 0, 1})
    port = Keyword.get(opts, :port, 4000)
    check_origin = Keyword.get(opts, :check_origin, true)

    LiveviewPlayground.ProxyRouter.set_router(router)

    Application.put_env(:liveview_playground, endpoint,
      http: [ip: ip, port: port],
      server: true,
      live_view: [signing_salt: "aaaaaaaa"],
      check_origin: check_origin,
      secret_key_base: String.duplicate("a", 64)
    )

    Application.put_env(:liveview_playground, :router, router)

    {:ok, _} = Supervisor.start_link([endpoint], strategy: :one_for_one)
    Process.sleep(:infinity)
  end
end
defmodule PageLive do
  use LiveviewPlaygroundWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :count, 0)}
  end

  def render(assigns) do
    ~H"""
    Counter: <%= @count %>
    <button phx-click="inc">+</button>
    <button phx-click="dec">-</button>
    """
  end

  def handle_event("inc", _params, socket) do
    {:noreply, assign(socket, :count, socket.assigns.count + 1)}
  end

  def handle_event("dec", _params, socket) do
    {:noreply, assign(socket, :count, socket.assigns.count - 1)}
  end
end

# listen on all interfaces, allowing connections from non-localhost. 
# Disable check-origin, as the external IP won't match the internal one. 
LVP.start(ip: {0, 0, 0, 0}, check_origin: false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment