Polyaxon v3 is coming →

Set up a Polyaxon code execution workspace

Enable sandbox execution on a Polyaxon service, reuse its image and compute settings, run commands through the SDK, and preserve results before cleanup.

August 4, 2026by Polyaxon
Two silver cubes on an amber-bordered workspace under Execution Workspace headline

A Polyaxon service can also be a workspace that an application controls through code. Enable plugins.sandbox to execute processes, exchange files, and open interactive terminals inside its main container, while keeping the service's image, resources, placement, and lifetime in the Polyaxon workload definition.

Use this for a GPU debugging workspace, a notebook whose files need to be inspected remotely, or a code-execution tool used by an application or agent. Polyaxon v2.16 introduced the sandbox plugin, execution runtime, and authenticated proxy routes. A sandbox-enabled workspace is a service run with additional interfaces, so it fits the same scheduling and lifecycle controls as other Polyaxon services.

The walkthrough starts with a disposable Python calculation, then explains how to reuse the pattern with your own service. It covers readiness, command results, file retrieval, and explicit cleanup.

Prepare the project and client

You need an existing quick-start project, a configured Polyaxon client, and compute that supports service workloads. Your deployment administrator must enable sandbox support.

Follow project creation and the sandbox quick start if those prerequisites are not already in place. The controller-side Python example requires the Polyaxon client installed in your local environment.

For generated or untrusted programs, choose the service's credentials, network access, and runtime isolation deliberately; the execution API does not itself define those policies.

Enable execution on your service

Add this fragment to the component that defines your service, preserving its existing plugin settings, image, command, and resource configuration:

plugins:
  sandbox: true

Apply the updated component when creating a new run. This changes the workload definition; it does not retrofit a running container. The deployment or compute agent must support sandbox services and the runtime setup required by your image.

The plugin specification requires /bin/sh in the image and an explicit run.container.command when you want to start your own application. Polyaxon wraps that command with its sandbox bootstrap. If your service previously relied only on the image's default entrypoint, make the intended startup command explicit before enabling the plugin; without a command, the sandbox runtime itself runs as the main process.

Your normal service process can continue to serve a notebook or application while sandbox commands operate in the same main container. Files and processes share that environment, so a debugging command can inspect the dependencies used by the application. Use workdir and command-specific environment values when a command needs a different working directory or settings.

WorkloadUseful sandbox actionConfiguration to retain
Python workspaceExecute a script and download its reportPython dependencies, writable workspace, timeout
GPU development serviceRun a short model or device diagnosticGPU requests, compatible image, placement preset
Notebook serviceInspect files or run a helper scriptNotebook startup command, persistent mounts, user permissions
Application serviceInspect installed packages or reproduce a local errorApplication entrypoint, environment, identity

For GPU profiles and queue selection, use sandbox resources. Shared presets let a platform team maintain these settings while application authors choose the workspace profile they need.

Define a disposable workspace

Clone the examples repository and open the shared lifecycle directory:

git clone https://github.com/polyaxon/polyaxon-examples.git
cd polyaxon-examples/blog/sandbox-lifecycle

Save this complete component as sandbox.yaml in that directory:

kind: component
version: 1.1
name: bounded-python-workspace

plugins:
  sandbox: true
  auth: false
  mountArtifactsStore: false

termination:
  timeout: 1800

run:
  kind: service
  volumes:
    - name: workspace
      emptyDir: {}
  container:
    image: python:3.11
    workingDir: /workspace
    command: ["sleep", "infinity"]
    resources:
      requests:
        cpu: "1"
        memory: 512Mi
      limits:
        cpu: "2"
        memory: 1Gi
    volumeMounts:
      - name: workspace
        mountPath: /workspace

The image tag is illustrative; use a reviewed digest in a repeatable production profile. The service stays alive to accept commands, with a 30-minute absolute timeout as a backstop.

The workspace uses emptyDir, so its files disappear when the Pod is replaced. Automatic Polyaxon authentication and artifact-store mounting are disabled because the calculation needs neither. Separately configured credentials and Kubernetes identity still require review.

Start, execute, and retrieve the result

The repository includes the shared lifecycle.py helper. Save the following script as run-workspace.py beside it and sandbox.yaml, then run it from that directory after completing the project and client setup. The helper reuses your configured credentials, sets a 10-second HTTP timeout without transport retries, and bounds repeated status polling separately from the service lifetime:

from polyaxon.client import SandboxClient

from lifecycle import make_run_client, stop_and_record, wait_for_running

run_client = make_run_client(project="quick-start")
run = run_client.create_from_polyaxonfile(
    polyaxonfile="sandbox.yaml",
    approved=True,
)
print("Execution run:", run.uuid)

try:
    wait_for_running(run_client, seconds=300)

    with SandboxClient(
        project="quick-start",
        run_uuid=run.uuid,
        client=run_client.client,
    ) as sandbox:
        sandbox.ping()
        result = sandbox.process.exec(
            command=[
                "python",
                "-c",
                (
                    "import json; from pathlib import Path; "
                    "Path('/workspace/report.json').write_text("
                    "json.dumps({'total': sum([2, 3, 5])}), "
                    "encoding='utf-8')"
                ),
            ],
            timeout_ms=10_000,
        )
        if result.timed_out or result.exit_code != 0:
            raise RuntimeError("Calculation did not complete successfully")

        sandbox.fs.download_file(
            path="/workspace/report.json",
            local_path="./workspace-report.json",
        )
        print("Saved workspace-report.json")
finally:
    cleanup = stop_and_record(run_client, seconds=30)

if not cleanup["confirmed"]:
    raise RuntimeError("Calculation finished, but service termination needs review")

The script checks a 300-second readiness deadline between status requests before checking sandbox health. An in-flight request still follows its HTTP timeout; this is not a hard real-time deadline. If the health endpoint is still unavailable, this example fails and attempts cleanup. A production controller can add a bounded health-check retry.

Cleanup writes cleanup-<run UUID>.json. A terminal status sets confirmed: true; a failed stop or status request leaves confirmed: false with the run identity to inspect. The helper does not turn an unconfirmed stop into success. Its deadline is independent of termination.timeout, which remains the workload backstop if the host disappears.

The command creates a small JSON report containing a total of 10. The controller downloads it before stopping the service. Closing the sandbox client alone would not stop the workload.

Turn the example into an application tool

Replace the fixed calculation with an approved operation or a controlled generated-code workflow. Validate input ownership and request size before dispatch, and check output schema and size before sharing results.

Use the process reference for streaming and background behavior, and the filesystem reference for file operations.

For durable platform evidence, persist approved reports through a trusted artifact workflow. This example downloads locally because the execution service has no artifact-store mount.

The same lifecycle applies as the application grows: provision deliberately, wait for readiness, execute within a budget, preserve useful outputs, and stop the environment.

Reuse the workspace deliberately

Keep the service running when several related commands need the same dependencies, checked-out files, or model cache. Attach subsequent clients using the explicit project and run UUID. Each process execution is a separate command; shell variables or a changed directory in one invocation do not automatically configure the next. Put shared settings in the Polyaxonfile, or pass them through the process API.

Choose persistence for the workflow. The example's emptyDir is convenient scratch space, and its downloaded report survives locally after cleanup. A reusable notebook workspace can use a PVC-backed connection. A service that logs durable experiment outputs needs the tracking library, authentication, and artifact-store setup described in Persist Outputs; re-enable the required plugins when adapting this deliberately minimal configuration.

Finally, separate the command budget from the workspace lifetime. timeout_ms bounds one execution request; termination.timeout bounds the service. For intermittently used notebooks or custom services, Polyaxon also supports idle culling with activity probes. Preserve the files you need, close clients when finished, and stop the service when the workspace is no longer useful.