Run a Jupyter notebook in a Modal Sandbox

This example demonstrates how to run a Jupyter notebook in a Modal Sandbox.

Setting up the Sandbox 

All Sandboxes are associated with an App.

We look up our app by name, creating it if it doesn’t exist.

We define a custom Docker image that has Jupyter and some other dependencies installed. Using a pre-defined image allows us to avoid re-installing packages on every Sandbox startup.

Starting a Jupyter server in a Sandbox 

Since we’ll be exposing a Jupyter server over the Internet, we need to create a password. We’ll use secrets from the standard library to create a token and then store it in a Modal Secret.

Now, we can start our Sandbox. Note our use of the encrypted_ports argument, which allows us to securely expose the Jupyter server to the public Internet. We use modal.enable_output() to print the Sandbox’s image build logs to the console.

Communicating with a Jupyter server 

Next, we print out a URL that we can use to connect to our Jupyter server. Note that we have to call Sandbox.tunnels to get the URL. The Sandbox is not publicly accessible until we do so.

Jupyter servers expose a REST API that you can use for programmatic manipulation.

For example, we can check the server’s status by sending a GET request to the /api/status endpoint.

We’ll now wait for the Jupyter server to be ready by hitting that endpoint.

You can now open this URL in your browser to access the Jupyter notebook!

When you’re done, terminate the sandbox using your Modal dashboard or by running Sandbox.from_id(sandbox.object_id).terminate().