A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add run in docker for remote urls (#2645)
Myles Scolnick1a640fcdf0b2
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex b443b24db1..ca7ab0e50a 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -21,6 +21,9 @@ from marimo._cli.export.commands import exportfrom marimo._cli.file_path import validate_namefrom marimo._cli.parse_args import parse_argsfrom marimo._cli.print import red+from marimo._cli.run_docker import (+ prompt_run_in_docker_container,+)from marimo._cli.upgrade import check_for_updates, print_latest_versionfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._server.file_router import AppFileRouter@@ -297,6 +300,19 @@ def edit() -> None:from marimo._cli.sandbox import prompt_run_in_sandbox+ # If file is a url, we prompt to run in docker+ # We only do this for remote files,+ # but later we can make this a CLI flag+ if name is not None and prompt_run_in_docker_container(name):+ from marimo._cli.run_docker import run_in_docker++ run_in_docker(+ name,+ port=port,+ debug=GLOBAL_SETTINGS.DEVELOPMENT_MODE,+ )+ return+if sandbox or prompt_run_in_sandbox(name):from marimo._cli.sandbox import run_in_sandbox@@ -581,6 +597,19 @@ def run() -> None:from marimo._cli.sandbox import prompt_run_in_sandbox+ # If file is a url, we prompt to run in docker+ # We only do this for remote files,+ # but later we can make this a CLI flag+ if prompt_run_in_docker_container(name):+ from marimo._cli.run_docker import run_in_docker++ run_in_docker(+ name,+ port=port,+ debug=GLOBAL_SETTINGS.DEVELOPMENT_MODE,+ )+ return+if sandbox or prompt_run_in_sandbox(name):from marimo._cli.sandbox import run_in_sandboxdiff --git a/marimo/_cli/print.py b/marimo/_cli/print.pyindex 6e18a7cb74..b2deb47fad 100644--- a/marimo/_cli/print.py+++ b/marimo/_cli/print.py@@ -28,6 +28,10 @@ def red(text: str, bold: bool = False) -> str:return prefix + text + "\033[0m"+def muted(text: str) -> str:+ return "\033[90m" + text + "\033[0m"++def echo(*args: Any, **kwargs: Any) -> None:import clickdiff --git a/marimo/_cli/run_docker.py b/marimo/_cli/run_docker.pynew file mode 100644index 0000000000..5ab154680f--- /dev/null+++ b/marimo/_cli/run_docker.py@@ -0,0 +1,194 @@+from __future__ import annotations++import subprocess+import sys+from typing import Optional++import click+from click import echo++from marimo import _loggers+from marimo._cli.print import green, muted, red+from marimo._config.settings import GLOBAL_SETTINGS+from marimo._utils.url import is_url++LOGGER = _loggers.marimo_logger()+++def prompt_run_in_docker_container(name: str | None) -> bool:+ if GLOBAL_SETTINGS.IN_SECURE_ENVIRONMENT:+ return False++ # Only prompt for remote files+ if name is None:+ return False+ if not is_url(name):+ return False++ if GLOBAL_SETTINGS.YES:+ return True++ return click.confirm(+ "This notebook is hosted on a remote server.\n"+ + green(+ "Would you like to run it in a secure docker container?",+ bold=True,+ ),+ default=True,+ )+++def _check_docker_installed() -> bool:+ try:+ subprocess.run(+ ["docker", "--version"], check=True, capture_output=True, text=True+ )+ return True+ except subprocess.CalledProcessError:+ return False+ except FileNotFoundError:+ return False+++def _check_docker_running() -> bool:+ try:+ subprocess.run(+ ["docker", "info"], check=True, capture_output=True, text=True+ )+ return True+ except subprocess.CalledProcessError:+ return False+++def echo_red(text: str) -> None:+ echo(red(text))+++# Run a marimo file in a docker container+# marimo edit https://github.com/some/file.py --docker+def _check_port_in_use(port: int) -> Optional[str]:+ try:+ result = subprocess.run(+ ["docker", "ps", "--format", "{{.ID}}\t{{.Ports}}", "--no-trunc"],+ check=True,+ capture_output=True,+ text=True,+ )+ for line in result.stdout.splitlines():+ container_id, ports = line.split("\t")+ if f":{port}->" in ports:+ return container_id+ except subprocess.CalledProcessError:+ pass+ return None+++def run_in_docker(+ file_path: str,+ *,+ port: Optional[int],+ debug: bool = False,+) -> None:+ echo(f"Starting {green('containerized')} marimo notebook")++ host = "0.0.0.0"+ if port is None:+ port = 8080++ if not _check_docker_installed():+ echo_red(+ "Docker is not installed. Please install Docker and try again."+ )+ sys.exit(1)++ if not _check_docker_running():+ echo_red(+ "Docker daemon is not running. Please start Docker and try again."+ )+ sys.exit(1)++ # Check if the port is already in use+ existing_container = _check_port_in_use(port)+ if existing_container:+ echo_red(+ f"Port {port} is already in use by container {existing_container}"+ )+ echo("To remove the existing container, run:")+ echo(muted(f" docker stop {existing_container}"))+ echo("Then try running this command again.")+ sys.exit(1)++ # Define the container image and command+ image = "ghcr.io/astral-sh/uv:0.4.21-python3.12-bookworm"+ container_command = [+ "uvx",+ "marimo",+ "-d" if debug else "",+ "edit",+ "--sandbox",+ "--no-token",+ "-p",+ f"{port}",+ "--host",+ host,+ file_path,+ ]+ # Remove empty strings from command+ container_command = [arg for arg in container_command if arg]++ # Construct the docker run command+ docker_command = [+ "docker",+ "run",+ "--rm",+ "-d",+ "-p",+ f"{port}:{port}",+ "-e",+ "MARIMO_MANAGE_SCRIPT_METADATA=true",+ "-e",+ "MARIMO_IN_SECURE_ENVIRONMENT=true",+ "-w",+ "/app",+ image,+ ] + container_command++ # Run the container+ echo(f"Running command: {muted(' '.join(docker_command))}")+ container_id = None+ try:+ result = subprocess.run(+ docker_command, check=True, capture_output=True, text=True+ )+ container_id = result.stdout.strip()+ echo(f"Container ID: {muted(container_id)}")+ echo(f"URL: {green(f'http://{host}:{port}')}")++ # Stream logs+ log_command = ["docker", "logs", "-f", container_id]+ with subprocess.Popen(+ log_command,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ universal_newlines=True,+ ) as process:+ try:+ for line in process.stdout or []:+ echo(line.strip())+ except KeyboardInterrupt:+ echo("Received keyboard interrupt.")+ except subprocess.CalledProcessError as e:+ echo_red(f"Failed to start Docker container: {e}")+ sys.exit(1)+ finally:+ echo("Stopping and removing container...")+ try:+ if container_id is not None:+ subprocess.run(+ ["docker", "stop", container_id],+ check=True,+ capture_output=True,+ )+ echo(muted("Container stopped and removed successfully"))+ except subprocess.CalledProcessError:+ echo_red("Failed to stop and remove container")diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex c62e3f39ca..f28ae27ca9 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -14,7 +14,7 @@ import clickfrom marimo import __version__, _loggersfrom marimo._cli.file_path import FileContentReader-from marimo._cli.print import bold, echo, green+from marimo._cli.print import bold, echo, green, mutedfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManager@@ -227,7 +227,7 @@ def run_in_sandbox(temp_file_path,] + cmd- echo(f"Running in a sandbox: {' '.join(cmd)}")+ echo(f"Running in a sandbox: {muted(' '.join(cmd))}")env = os.environ.copy()env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"diff --git a/marimo/_config/settings.py b/marimo/_config/settings.pyindex 27e905dc0a..23b928c110 100644--- a/marimo/_config/settings.py+++ b/marimo/_config/settings.py@@ -18,6 +18,9 @@ class GlobalSettings:MANAGE_SCRIPT_METADATA: bool = os.getenv("MARIMO_MANAGE_SCRIPT_METADATA", "false") in ("true", "1")+ IN_SECURE_ENVIRONMENT: bool = os.getenv(+ "MARIMO_IN_SECURE_ENVIRONMENT", "false"+ ) in ("true", "1")GLOBAL_SETTINGS = GlobalSettings()diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex ef2d043e37..a7bb461c57 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -708,3 +708,28 @@ def test_cli_run_sandbox_prompt_yes() -> None:assert p.poll() is None_check_started(port)p.kill()+++HAS_DOCKER = DependencyManager.which("docker")+++ HAS_DOCKER, reason="docker is required to be not installed"+)+def test_cli_run_docker_remote_url():+ remote_url = "https://example.com/notebook.py"+ p = subprocess.Popen(+ [+ "marimo",+ "-y",+ "edit",+ remote_url,+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ # Should fail with missing docker+ assert p.returncode != 0+ assert p.stdout is not None+ assert "Docker is not installed" in p.stdout.read().decode()