### Start Instance C# Example Source: https://cloud.morph.so/docs/api-reference/start-instance-instance-post A C# example using HttpClient to send a POST request to start an instance. It shows how to set headers, content, and handle the response. ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/instance"); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Authorization", "Bearer "); var content = new StringContent("{\n \"metadata\": {},\n \"ttl_seconds\": 0,\n \"ttl_action\": \"stop\"\n}", null, "application/json"); request.Content = content; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` -------------------------------- ### Complete Docker BuildKit Example Setup Source: https://cloud.morph.so/docs/examples/docker-buildkit This section provides a comprehensive guide to setting up a Docker BuildKit environment on Morph Cloud. It includes installing dependencies, setting the API key, cloning an example repository, and running a setup script. The example covers Docker installation with BuildKit, multi-stage Dockerfiles, health checks, service exposure, and snapshot creation for reusable environments. ```Shell # Install dependencies uv pip install morphcloud # Set your API key export MORPH_API_KEY='your-key-here' # Clone and run the complete example git clone https://github.com/morph-labs/morphcloud-examples-public.git cd morphcloud-examples-public/docker-buildkit python docker-buildkit_setup.py ``` -------------------------------- ### Complete Setup Script for Claude Code Development Source: https://cloud.morph.so/docs/examples/claude-code This section provides the complete installation and setup commands, including installing the 'uv' package manager, setting up a virtual environment, installing the Morph Cloud SDK, setting API keys for both Morph Cloud and Anthropic, and finally running the Python setup script. It outlines the steps involved in preparing a development environment. ```Bash # Install dependencies curl -LsSf https://astral.sh/uv/install.sh | sh source ~/.local/bin/env uv venv && source .venv/bin/activate uv pip install morphcloud # Set your API keys export MORPH_API_KEY='your-key-here' export ANTHROPIC_API_KEY='your-claude-key-here' # Run the setup script uv run python claude_dev_setup.py ``` -------------------------------- ### Start an Instance from a Snapshot Source: https://cloud.morph.so/docs/developers Launches a new instance based on a previously created snapshot. The instance is configured with a time-to-live (TTL) in seconds. ```Python instance = client.instances.start(snapshot.id, ttl_seconds = 3600) print(f"Started instance: {instance.id}") ``` ```Bash INSTANCE=$(morphcloud instance start $SNAPSHOT --ttl-seconds=3600) echo "Started instance: $INSTANCE" ``` ```TypeScript const instance = await client.instances.start({ snapshotId: snapshot.id, ttlSeconds: 3600 }); console.log(`Started instance: ${instance.id}`); ``` -------------------------------- ### Install Morph Cloud Libraries and Set API Key Source: https://cloud.morph.so/docs/developers Installs the Morph Cloud client library for Python and TypeScript, and sets the API key as an environment variable. This is a prerequisite for interacting with the Morph Cloud API. ```Bash # Python developers pip install morphcloud # For Python # TypeScript developers npm install morphcloud # For TypeScript # Set your API key (get it from cloud.morph.so) export MORPH_API_KEY='your-api-key-here' ``` -------------------------------- ### Start New Instance from Snapshot (Bash) Source: https://cloud.morph.so/docs/developers This bash script starts a new instance from a given snapshot ID using the `morphcloud instance start` command. It stores the new instance identifier. ```bash # Start new instance from snapshot NEW_INSTANCE=$(morphcloud instance start $NEW_SNAPSHOT) echo "Started new instance: $NEW_INSTANCE" ``` -------------------------------- ### Morph Cloud CLI Usage Source: https://cloud.morph.so/docs/documentation/setup/installation-guide Demonstrates how to check the help command for the Morph Cloud CLI after installation. ```Bash morphcloud --help ``` -------------------------------- ### Get Started with Morph Cloud and Playwright (Python/Bash) Source: https://cloud.morph.so/docs/examples/browser-automation A quick start guide to launching browser automation environments with Playwright support on Morph Cloud. It includes installing necessary dependencies, setting the API key, cloning an example repository, and running a Python script for browser automation tasks like web scraping. ```bash # Install dependencies uv pip install morphcloud playwright # Set your API key export MORPH_API_KEY='your-key-here' # Clone and run the complete example git clone https://github.com/morph-labs/morph-python-sdk.git cd morph-python-sdk/examples python browser_example.py ``` -------------------------------- ### Start New Instance from Snapshot (TypeScript) Source: https://cloud.morph.so/docs/developers This TypeScript code starts a new instance from a snapshot. It requires a `client` object and the `snapshotId` of the snapshot to use, then logs the ID of the newly started instance. ```typescript // Start new instance from snapshot const newInstance = await client.instances.start({ snapshotId: newSnapshot.id }); console.log(`Started new instance: ${newInstance.id}`); ``` -------------------------------- ### Start New Instance from Snapshot (Python) Source: https://cloud.morph.so/docs/developers This Python code starts a new instance using a previously created snapshot ID. It assumes a `client` object and a `new_snapshot` object are available and prints the ID of the new instance. ```python # Start new instance from snapshot new_instance = client.instances.start(new_snapshot.id) print(f"Started new instance: {new_instance.id}") ``` -------------------------------- ### Run Hello World with Morph Cloud (CLI) Source: https://cloud.morph.so/docs/documentation/setup/hello-world This command-line interface (CLI) example demonstrates the process of creating a snapshot, starting an instance, executing a 'Hello World' command, and stopping the instance using Morph Cloud's command-line tools. ```Bash # 1. Create a new snapshot SNAPSHOT_ID=$(morphcloud snapshot create --image morphvm-minimal --vcpus 1 --memory 1024 --disk-size 10000 | grep -o 'snapshot_[a-zA-Z0-9]*') # 2. Start an instance from the snapshot INSTANCE_ID=$(morphcloud instance start $SNAPSHOT_ID | grep -o 'morphvm_[a-zA-Z0-9]*') # 3. Run a hello world command morphcloud instance exec $INSTANCE_ID echo "Hello, Morph Cloud!" # 4. Stop the instance when done morphcloud instance stop $INSTANCE_ID ``` -------------------------------- ### Create Snapshot and Start New Instance (Shell) Source: https://cloud.morph.so/docs/developers This shell script automates the process of creating a snapshot of a running instance and then starting a new instance from that snapshot. It extracts snapshot and instance IDs and checks a counter file within the new instance. ```shell echo "Creating snapshot of running instance..." NEW_SNAPSHOT_OUTPUT=$($MORPH_CMD instance snapshot $INSTANCE 2>&1) NEW_SNAPSHOT=$(echo "$NEW_SNAPSHOT_OUTPUT" | grep -o 'snapshot_[a-zA-Z0-9]*' | tail -1) NEW_INSTANCE_OUTPUT=$($MORPH_CMD instance start $NEW_SNAPSHOT 2>&1) NEW_INSTANCE=$(echo "$NEW_INSTANCE_OUTPUT" | grep -o 'morphvm_[a-zA-Z0-9]*' | tail -1) echo "Started new instance: $NEW_INSTANCE" # Check counter in new instance NEW_COUNTER=$($MORPH_CMD instance exec $NEW_INSTANCE "cat /root/counter.txt" 2>/dev/null | grep -v "Executing" | grep -v "Command execution") echo "Counter in new instance: $NEW_COUNTER" # Wait to verify counter continues incrementing echo "Waiting to verify counter continues in new instance..." sleep 10 FINAL_COUNTER=$($MORPH_CMD instance exec $NEW_INSTANCE "cat /root/counter.txt" 2>/dev/null | grep -v "Executing" | grep -v "Command execution") echo "Counter after waiting in new instance: $FINAL_COUNTER" echo "✨ Success! The background process continued exactly where it left off." echo "Original instance counter: $INCREMENTED_COUNTER → New instance counter: $FINAL_COUNTER" echo "Instances running: $INSTANCE and $NEW_INSTANCE" ``` -------------------------------- ### Install Morph Cloud SDK (TypeScript) Source: https://cloud.morph.so/docs/documentation/setup/installation-guide Installs the Morph Cloud SDK for TypeScript using npm. After installation, the client can be imported and used in your project. ```Bash npm install morphcloud ``` ```TypeScript import { MorphCloudClient } from 'morphcloud'; const client = new MorphCloudClient(); ``` -------------------------------- ### Install Morph Cloud SDK (Python) Source: https://cloud.morph.so/docs/documentation/setup/installation-guide Installs the Morph Cloud SDK for Python. This involves creating and activating a virtual environment, then using pip to install the package. Requires Python 3.11 or newer. ```Bash # requires python3.11 or newer # create a new virtual environment python -m venv .venv # activate the new virtual environment source .venv/bin/activate # install morphcloud pip install morphcloud ``` ```Python from morphcloud.api import MorphCloudClient client = MorphCloudClient() ``` -------------------------------- ### Setup Claude Code Development Environment Source: https://cloud.morph.so/docs/examples/claude-code A Python script to automate the setup of a development environment for Claude Code on Morph Cloud. It starts a Morph Cloud instance, installs the Claude Code CLI and other development tools, configures Git, creates a workspace, sets up the API key in bashrc, and creates a tmux session. Finally, it creates a snapshot of the configured environment. ```Python # claude_dev_setup.py from morphcloud.api import MorphCloudClient def setup_claude_dev_environment(): client = MorphCloudClient() # Create a new instance instance = client.instances.start() print(f"Instance started: {instance.id}") # Install Claude Code CLI instance.exec("curl -fsSL https://claude.ai/install.sh | sh") instance.exec("npm install -g @anthropic-ai/claude-code") # Install development tools instance.exec("sudo apt update") instance.exec("sudo apt install -y git gh nodejs npm python3 python3-pip tmux") # Configure Git and GitHub CLI instance.exec("git config --global init.defaultBranch main") # Set up workspace directory instance.exec("mkdir -p /workspace") instance.exec("cd /workspace") # Configure Claude Code with API key instance.exec("echo 'export ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY' >> ~/.bashrc") # Create tmux session for Claude instance.exec("tmux new-session -d -s claude-session") # Create snapshot snapshot = instance.snapshot() print(f"Snapshot created: {snapshot.id}") return snapshot.id if __name__ == "__main__": snapshot_id = setup_claude_dev_environment() print(f"Setup complete! Use snapshot ID: {snapshot_id}") ``` -------------------------------- ### Run Hello World with Morph Cloud (Python) Source: https://cloud.morph.so/docs/documentation/setup/hello-world This Python script demonstrates how to create a Morph Cloud snapshot, start an instance from it, execute a 'Hello World' command, and then stop the instance. It utilizes the MorphCloudClient for interacting with the Morph Cloud API. ```Python from morphcloud.api import MorphCloudClient # Initialize client client = MorphCloudClient() # 1. Create a new snapshot (or list existing ones) new_snapshot = client.snapshots.create( image_id="morphvm-minimal", vcpus=1, memory=1024, # MB disk_size=10000 # MB ) print(f"Created snapshot: {new_snapshot.id}") # 2. Start an instance from the snapshot instance = client.instances.start(snapshot_id=new_snapshot.id) print(f"Started instance: {instance.id}") # Wait for instance to be ready instance.wait_until_ready() # 3. Run a hello world command result = instance.exec(command="echo 'Hello, Morph Cloud!'") print(f"Command output: {result.stdout}") # 4. Stop the instance when done instance.stop() print("Instance stopped") ``` -------------------------------- ### Create and Configure Snapshot (TypeScript) Source: https://cloud.morph.so/docs/documentation/instances/snapshot-setup Demonstrates creating a Morph Cloud snapshot with specified resources, chaining setup commands for package installation and Docker configuration, and running a headless Chrome instance via Docker. Each setup step is cached. ```TypeScript import { MorphCloudClient } from 'morphcloud'; const client = new MorphCloudClient(); async function setupSnapshot() { // Create a snapshot with resource requirements and a unique digest. let snapshot = await client.snapshots.create({ vcpus: 1, memory: 4096, disk_size: 8192, digest: "chromebox-1-1", }); // Chain setup steps; each step is cached. snapshot = await snapshot.setup("apt update -y"); snapshot = await snapshot.setup("apt install -y docker.io"); snapshot = await snapshot.setup("systemctl enable docker"); snapshot = await snapshot.setup("systemctl start docker"); snapshot = await snapshot.setup("docker network create morph-net"); snapshot = await snapshot.setup( `docker run -d --network morph-net --name headless-chrome \ zenika/alpine-chrome \ --headless --no-sandbox --disable-gpu --disable-dev-shm-usage \ --remote-debugging-port=9222 --remote-debugging-address=0.0.0.0` ); snapshot = await snapshot.setup( `cat <<'EOF' > /tmp/default.conf server { listen 80; location / { proxy_pass http://headless-chrome:9222; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host localhost; } location /json/ { proxy_pass http://headless-chrome:9222; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host localhost; proxy_set_header Accept-Encoding ""; sub_filter_types application/json; sub_filter_once off; sub_filter "ws://localhost" "wss://$http_host"; } } EOF` ); snapshot = await snapshot.setup( `docker run -d --network morph-net --name chrome-proxy \ -p 9222:80 \ -v /tmp/default.conf:/etc/nginx/conf.d/default.conf:ro \ nginx:alpine` ); // Start an instance using the snapshot. const instance = await client.instances.start({ snapshot_id: snapshot.id }); console.log(`Instance started with ID: ${instance.id}`); } setupSnapshot().catch(error => { console.error("An error occurred:", error); }); ``` -------------------------------- ### Create Snapshot and Start New Instance (TypeScript) Source: https://cloud.morph.so/docs/developers This TypeScript code uses the MorphCloudClient to create a snapshot of a running instance and then start a new instance from that snapshot. It also initiates a background counter process within the instance and verifies its incrementing behavior. ```typescript // tutorial.ts import { MorphCloudClient } from 'morphcloud'; async function main() { const client = new MorphCloudClient(); console.log("Creating snapshot and starting instance..."); const snapshot = await client.snapshots.create({ imageId: "morphvm-minimal", vcpus: 1, memory: 4096, diskSize: 16384 }); const instance = await client.instances.start({ snapshotId: snapshot.id }); console.log(`Started instance: ${instance.id}`); // Create counter script console.log("Starting counter..."); const nohupResult = await instance.exec("nohup bash -c 'count=1; echo $count > /root/counter.txt; while [ $count -le 100 ]; do sleep 5; count=$((count + 1)); echo $count > /root/counter.txt; done' > /dev/null 2>&1 & echo $!"); const pid = nohupResult.stdout.trim(); console.log(`Background process PID: ${pid}`); // Check initial counter value await new Promise(resolve => setTimeout(resolve, 2000)); const initialCounter = (await instance.exec("cat /root/counter.txt")).stdout; console.log(`Initial counter: ${initialCounter}`); // Wait for counter to increment console.log("Waiting for counter to increment..."); await new Promise(resolve => setTimeout(resolve, 10000)); const incrementedCounter = (await instance.exec("cat /root/counter.txt")).stdout; console.log(`Counter after waiting: ${incrementedCounter}`); // Kill the background process await instance.exec(`kill ${pid}`); console.log(`Killed background process ${pid}`); // Create snapshot and start new instance console.log("Creating snapshot of running instance..."); const newSnapshot = await instance.snapshot(); const newInstance = await client.instances.start({ snapshotId: newSnapshot.id }); console.log(`Started new instance: ${newInstance.id}`); // Check counter in new instance const newCounter = (await newInstance.exec("cat /root/counter.txt")).stdout; console.log(`Counter in new instance: ${newCounter}`); // Wait to verify counter continues incrementing console.log("Waiting to verify counter continues in new instance..."); await new Promise(resolve => setTimeout(resolve, 10000)); const finalCounter = (await newInstance.exec("cat /root/counter.txt")).stdout; console.log(`Counter after waiting in new instance: ${finalCounter}`); console.log("\n✨ Success! The background process continued exactly where it left off."); console.log(`Original instance counter: ${incrementedCounter} → New instance counter: ${finalCounter}`); } main().catch(error => console.error('Error:', error)); ``` -------------------------------- ### Start Instance from Snapshot (Python) Source: https://cloud.morph.so/docs/documentation/instances/snapshot-setup Starts a Morph Cloud instance using a previously created snapshot and exposes an HTTP service for a browser. The instance is managed within a context manager, ensuring proper cleanup. ```Python from morphcloud import Browser, BrowserConfig # Assuming 'client' and 'snapshot' are already defined and initialized # Example: client = MorphCloudClient() # Example: snapshot = client.snapshots.get("your_snapshot_id") with client.instances.start(snapshot.id, ttl_seconds=3600) as instance: url = instance.expose_http_service("browser", 9222) print(f"Instance ID: {instance.id}") print(f"Browser service URL: {url}") browser = Browser(config=BrowserConfig(cdp_url=url)) try: # Use the browser instance here yield browser finally: pass ``` -------------------------------- ### Complete Remote Desktop Setup Source: https://cloud.morph.so/docs/examples/remote-desktop A comprehensive example demonstrating the setup of a full Linux desktop environment (XFCE) with VNC server, noVNC web interface, service exposure, and snapshot creation for reusable desktop environments. ```bash # Install dependencies uv pip install morphcloud # Set your API key export MORPH_API_KEY='your-key-here' # Clone and run the complete example git clone https://github.com/morph-labs/morphcloud-examples-public.git cd morphcloud-examples-public/remote-desktop python remote-desktop_setup.py ``` -------------------------------- ### CLI (bash): Demonstrate Morph Cloud State Preservation Source: https://cloud.morph.so/docs/developers This bash script utilizes the Morph Cloud CLI (accessed via `python -m morphcloud.cli`) to demonstrate state preservation. It creates a snapshot, starts an instance, executes a background counter script on the instance, and then verifies that the counter continues in a newly started instance from the same snapshot. Requires the MORPH_API_KEY environment variable to be set. ```bash #!/bin/bash # Note: The morphcloud CLI is provided through the Python package. # Run with: python -m morphcloud.cli # tutorial_fixed.sh - Demonstrate perfect state preservation with Morph Cloud # Define the CLI command MORPH_CMD="python -m morphcloud.cli" # Check for required dependencies if [ -z "$MORPH_API_KEY" ]; then echo "Error: MORPH_API_KEY environment variable must be set" exit 1 fi # Create snapshot and start instance echo "Creating snapshot and starting instance..." SNAPSHOT_OUTPUT=$($MORPH_CMD snapshot create --image-id=morphvm-minimal --vcpus=1 --memory=128 --disk-size=700 2>&1) SNAPSHOT=$(echo "$SNAPSHOT_OUTPUT" | grep -o 'snapshot_[a-zA-Z0-9]*' | tail -1) INSTANCE_OUTPUT=$($MORPH_CMD instance start $SNAPSHOT 2>&1) INSTANCE=$(echo "$INSTANCE_OUTPUT" | grep -o 'morphvm_[a-zA-Z0-9]*' | tail -1) echo "Started instance: $INSTANCE" # Create and start counter script echo "Creating counter script..." $MORPH_CMD instance exec $INSTANCE "bash -c 'cat > /root/counter_script.sh << \"EOF\" #!/bin/bash count=1 echo $count > /root/counter.txt while [ $count -le 100 ]; do sleep 5 count=$((count + 1)) echo $count > /root/counter.txt done EOF'" > /dev/null 2>&1 $MORPH_CMD instance exec $INSTANCE "chmod +x /root/counter_script.sh" > /dev/null 2>&1 $MORPH_CMD instance exec $INSTANCE "nohup /root/counter_script.sh > /dev/null 2>&1 &" > /dev/null 2>&1 # Check initial counter value and wait for increment sleep 2 INITIAL_COUNTER=$($MORPH_CMD instance exec $INSTANCE "cat /root/counter.txt" 2>/dev/null | grep -v "Executing" | grep -v "Command execution") echo "Initial counter: $INITIAL_COUNTER" echo "Waiting for counter to increment..." sleep 10 INCREMENTED_COUNTER=$($MORPH_CMD instance exec $INSTANCE "cat /root/counter.txt" 2>/dev/null | grep -v "Executing" | grep -v "Command execution") echo "Counter after waiting: $INCREMENTED_COUNTER" ``` -------------------------------- ### Complete Example: Setup and Authenticate HTTP Service (Python) Source: https://cloud.morph.so/docs/documentation/instances/http-services Demonstrates setting up a simple HTTP server within an instance, exposing it with API key authentication, and preparing for authenticated requests. Includes creating a server script and writing it to the instance. ```Python from morphcloud.api import MorphCloudClient import time import requests from http.server import HTTPServer, BaseHTTPRequestHandler # Start a simple HTTP server within the instance client = MorphCloudClient() instance_id = "morphvm_abc123" instance = client.instances.get(instance_id=instance_id) # Create a simple HTTP server script server_script = """ from http.server import HTTPServer, BaseHTTPRequestHandler class SimpleHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'Hello from Morph Cloud!') server = HTTPServer(('0.0.0.0', 8081), SimpleHandler) print('Server started on port 8081') server.serve_forever() """ # Write the server script to the instance instance.exec("mkdir -p /app") instance.exec(f"cat > /app/server.py << 'EOF'\n{server_script}\nEOF") ``` -------------------------------- ### Create a Snapshot using Morph Cloud Source: https://cloud.morph.so/docs/developers Creates a new snapshot from a specified base image with defined vCPU, memory, and disk size. This snapshot can then be used to launch new instances. ```Python from morphcloud.api import MorphCloudClient client = MorphCloudClient() snapshot = client.snapshots.create( image_id="morphvm-minimal", vcpus=1, memory=4096, disk_size=16384 ) print(f"Created snapshot: {snapshot.id}") ``` ```Bash # Using the morphcloud CLI SNAPSHOT=$(morphcloud snapshot create --image-id=morphvm-minimal --vcpus=1 --memory=4096 --disk-size=16384) echo "Created snapshot: $SNAPSHOT" ``` ```TypeScript import { MorphCloudClient } from 'morphcloud'; const client = new MorphCloudClient(); const snapshot = await client.snapshots.create({ imageId: "morphvm-minimal", vcpus: 1, memory: 4096, diskSize: 16384 }); console.log(`Created snapshot: ${snapshot.id}`); ``` -------------------------------- ### Create Instance Snapshot (Python) Source: https://cloud.morph.so/docs/developers This Python code creates a snapshot of a running instance. It assumes an `instance` object is already available and prints the ID of the newly created snapshot. ```python # Create snapshot of running instance print("Creating snapshot of running instance...") new_snapshot = instance.snapshot() print(f"Created snapshot: {new_snapshot.id}") ``` -------------------------------- ### Python: Demonstrate Morph Cloud State Preservation Source: https://cloud.morph.so/docs/developers This Python script demonstrates Morph Cloud's ability to preserve the state of a running process. It creates a snapshot of an instance, starts a new instance from that snapshot, and verifies that a background counter process continues from where it left off. Dependencies include the 'morphcloud' Python package. ```Python # tutorial.py from morphcloud.api import MorphCloudClient import time # Demonstrate perfect state preservation with Morph Cloud client = MorphCloudClient() print("Creating snapshot and starting instance...") snapshot = client.snapshots.create(image_id="morphvm-minimal", vcpus=1, memory=4096, disk_size=16384) instance = client.instances.start(snapshot.id) print(f"Started instance: {instance.id}") nohup_result = instance.exec("nohup bash -c 'count=1; echo $count > /root/counter.txt; while [ $count -le 100 ]; do sleep 5; count=$((count + 1)); echo $count > /root/counter.txt; done' > /dev/null 2>&1 & echo $!") pid = nohup_result.stdout.strip() print(f"Background process PID: {pid}") # Check initial counter value import time time.sleep(2) initial_counter = instance.exec("cat /root/counter.txt").stdout print(f"Initial counter: {initial_counter}") # Wait for counter to increment print("Waiting for counter to increment...") time.sleep(10) incremented_counter = instance.exec("cat /root/counter.txt").stdout print(f"Counter after waiting: {incremented_counter}") # Kill the background process instance.exec(f"kill {pid}") print(f"Killed background process {pid}") # Create snapshot and start new instance print("Creating snapshot of running instance...") new_snapshot = instance.snapshot() new_instance = client.instances.start(new_snapshot.id) print(f"Started new instance: {new_instance.id}") # Check counter in new instance new_counter = new_instance.exec("cat /root/counter.txt").stdout print(f"Counter in new instance: {new_counter}") # Wait to verify counter continues incrementing print("Waiting to verify counter continues in new instance...") time.sleep(10) final_counter = new_instance.exec("cat /root/counter.txt").stdout print(f"Counter after waiting in new instance: {final_counter}") print("\n✨ Success! The background process continued exactly where it left off.") print(f"Original instance counter: {incremented_counter} → New instance counter: {final_counter}") ``` -------------------------------- ### Python: Setup Docker, Nginx, and Headless Chrome Snapshot Source: https://cloud.morph.so/docs/documentation/instances/snapshot-setup This Python script utilizes the Morph Cloud SDK to create a custom snapshot. It installs Docker, sets up a Docker network, runs headless Chrome and Nginx containers, and configures Nginx as a proxy to the Chrome instance. The setup steps are chained and cached for efficiency. ```Python #!/usr/bin/env python3 # Example: Custom Snapshot Setup with Morph Cloud import os import asyncio from morphcloud.api import MorphCloudClient client = MorphCloudClient() # Create a snapshot with resource requirements and an identifying digest. snapshot = client.snapshots.create( vcpus=1, memory=4096, disk_size=8192, digest="chromebox-1-1", ) # Chain setup steps; each step is cached. snapshot = ( snapshot.setup("apt update -y") .setup("apt install -y docker.io") .setup("systemctl enable docker") .setup("systemctl start docker") .setup("docker network create morph-net") .setup( "docker run -d --network morph-net --name headless-chrome " "zenika/alpine-chrome " "--headless --no-sandbox --disable-gpu --disable-dev-shm-usage " "--remote-debugging-port=9222 --remote-debugging-address=0.0.0.0" ) .setup( "\"\ncat <<'EOF' > /tmp/default.conf server { listen 80; location / { proxy_pass http://headless-chrome:9222; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection \"upgrade\"; proxy_set_header Host localhost; } location /json/ { proxy_pass http://headless-chrome:9222; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection \"upgrade\"; proxy_set_header Host localhost; proxy_set_header Accept-Encoding ""; sub_filter_types application/json; sub_filter_once off; sub_filter \"ws://localhost\" \"wss://$http_host\"; } } EOF \"" ) .setup( "docker run -d --network morph-net --name chrome-proxy " "-p 9222:80 " "-v /tmp/default.conf:/etc/nginx/conf.d/default.conf:ro " "nginx:alpine" ) ) ``` -------------------------------- ### Start Instance API Request Source: https://cloud.morph.so/docs/api-reference/start-instance-instance-post This snippet demonstrates how to initiate a POST request to the /api/instance endpoint to start a new instance. It includes setting the snapshot ID, metadata, TTL, and TTL action. ```http POST /api/instance?snapshot_id= HTTP/1.1 Host: your-api-host.com Content-Type: application/json Authorization: Bearer { "metadata": {}, "ttl_seconds": 0, "ttl_action": "stop" } ``` -------------------------------- ### Python: Install tmux, Start Server, Expose HTTP, Authenticate Request Source: https://cloud.morph.so/docs/documentation/instances/http-services This Python script installs tmux, starts a Python server in the background using tmux, exposes the HTTP service with API key authentication, makes an authenticated request, and cleans up the service. It uses the `instance.exec`, `instance.expose_http_service`, and `instance.hide_http_service` methods. ```Python import requests import time from morphcloud import MorphCloudClient client = MorphCloudClient() instance = client.instances.get(instance_id="morphvm_abc123") # Install tmux and start the server in the background instance.exec("apt-get update && apt-get install -y tmux python3 pip") instance.exec("cd /app && tmux new-session -d -s server 'python3 server.py'") time.sleep(5) # Give the server time to start # Expose the HTTP service with API key authentication service_url = instance.expose_http_service(name="secure-service", port=8081, auth_mode="api_key") # Make an authenticated request to the service headers = {"Authorization": f"Bearer {client.api_key}"} response = requests.get(service_url, headers=headers) print(f"Response: {response.status_code} {response.text}") # Clean up when done instance.hide_http_service(name="secure-service") # Take a snapshot before stopping snapshot = instance.snapshot() # Stop the instance # instance.stop() # print("Instance stopped") ``` -------------------------------- ### Create Instance Snapshot (Bash) Source: https://cloud.morph.so/docs/developers This bash script creates a snapshot of a running instance using the `morphcloud instance snapshot` command. It captures the snapshot ID for later use. ```bash # Create snapshot of running instance echo "Creating snapshot of running instance..." NEW_SNAPSHOT=$(morphcloud instance snapshot $INSTANCE) echo "Created snapshot: $NEW_SNAPSHOT" ``` -------------------------------- ### Create Instance Snapshot (TypeScript) Source: https://cloud.morph.so/docs/developers This TypeScript code creates a snapshot of the current instance. It uses the `instance.snapshot()` method and logs the ID of the created snapshot. ```typescript // Create snapshot of running instance console.log("Creating snapshot of running instance..."); const newSnapshot = await instance.snapshot(); console.log(`Created snapshot: ${newSnapshot.id}`); ``` -------------------------------- ### C# Example for Listing Snapshots Source: https://cloud.morph.so/docs/api-reference/list-snapshots-snapshot-get This C# code demonstrates how to use HttpClient to make a GET request to the /api/snapshot endpoint, including setting the Authorization header and handling the response. ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "/api/snapshot"); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Authorization", "Bearer "); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` -------------------------------- ### Execute a Background Process in an Instance Source: https://cloud.morph.so/docs/developers Executes a bash script within a running instance that creates a counter file, increments it every 5 seconds, and runs in the background. It also demonstrates checking the counter's value and killing the process. ```Python nohup_result = instance.exec("nohup bash -c 'count=1; echo $count > /root/counter.txt; while [ $count -le 100 ]; do sleep 5; count=$((count + 1)); echo $count > /root/counter.txt; done' > /dev/null 2>&1 & echo $!") pid = nohup_result.stdout.strip() print(f"Background process PID: {pid}") # Check initial counter value import time time.sleep(2) initial_counter = instance.exec("cat /root/counter.txt").stdout print(f"Initial counter: {initial_counter}") # Wait for counter to increment print("Waiting for counter to increment...") time.sleep(10) incremented_counter = instance.exec("cat /root/counter.txt").stdout print(f"Counter after waiting: {incremented_counter}") # Kill the background process instance.exec(f"kill {pid}") print(f"Killed background process {pid}") ``` ```Bash # Create counter script morphcloud instance exec $INSTANCE "cat > /root/counter_script.sh << 'EOF' #!/bin/bash count=1 echo $count > /root/counter.txt while [ $count -le 100 ]; do sleep 5 count=$((count + 1)) echo $count > /root/counter.txt done EOF" morphcloud instance exec $INSTANCE "chmod +x /root/counter_script.sh" morphcloud instance exec $INSTANCE "nohup /root/counter_script.sh > /dev/null 2>&1 &" # Check initial counter value sleep 2 INITIAL_COUNTER=$(morphcloud instance exec $INSTANCE "cat /root/counter.txt") echo "Initial counter: $INITIAL_COUNTER" ``` -------------------------------- ### Start Instance Request Body Schema Source: https://cloud.morph.so/docs/api-reference/start-instance-instance-post The JSON schema for the request body when starting an instance. It includes optional fields like metadata, ttl_seconds, and ttl_action. ```json { "metadata": {}, "ttl_seconds": 0, "ttl_action": "stop" } ``` -------------------------------- ### Install Morph Cloud SDK Source: https://cloud.morph.so/docs/examples/claude-code Installs the Morph Cloud Python SDK using the 'uv' package manager. This is a prerequisite for interacting with Morph Cloud services. ```Bash uv pip install morphcloud ``` -------------------------------- ### Execute Command and Wait for Counter Increment (Bash) Source: https://cloud.morph.so/docs/developers This bash script waits for a counter file on a remote instance to be incremented. It uses `morphcloud instance exec` to read the counter file and `sleep` to pause execution. ```bash echo "Waiting for counter to increment..." sleep 10 INCREMENTED_COUNTER=$(morphcloud instance exec $INSTANCE "cat /root/counter.txt") echo "Counter after waiting: $INCREMENTED_COUNTER" ``` -------------------------------- ### Verify State Preservation of Counter (Python) Source: https://cloud.morph.so/docs/developers This Python code verifies that the counter process continues correctly in a new instance launched from a snapshot. It reads the counter file, waits, and reads it again to confirm incrementation. ```python # Check counter in new instance new_counter = new_instance.exec("cat /root/counter.txt").stdout print(f"Counter in new instance: {new_counter}") # Wait to verify counter continues incrementing print("Waiting to verify counter continues in new instance...") time.sleep(10) final_counter = new_instance.exec("cat /root/counter.txt").stdout print(f"Counter after waiting in new instance: {final_counter}") print("\n✨ Success! The background process continued exactly where it left off.") print(f"Original instance counter: {incremented_counter} → New instance counter: {final_counter}") ``` -------------------------------- ### Start Auto-Scaling Agent Workspace (Python) Source: https://cloud.morph.so/docs/examples/auto-scale-agent-workspaces This Python code demonstrates how to start an auto-scaling agent workspace. It initializes a MorphCloudClient, starts an instance with a specified Time-To-Live (TTL), exposes an HTTP service for the agent, and enables wake-on-request for HTTP and SSH. ```Python import os from morphcloud.api import MorphCloudClient class AutoScalingAgent: def __init__(self, snapshot_id: str, ttl_minutes: int = 15): self.client = MorphCloudClient(api_key=os.getenv("MORPH_API_KEY")) self.snapshot_id = snapshot_id self.ttl_seconds = ttl_minutes * 60 self.instance = None def start(self): """Start the agent workspace with auto-scaling configuration.""" # 1. Start instance with TTL self.instance = self.client.instances.start( snapshot_id=self.snapshot_id, ttl_seconds=self.ttl_seconds, ttl_action="pause" ) print(f"Instance started: {self.instance.id}") # 2. Expose HTTP service (agent on port 8080) service = self.instance.expose_http_service("agent", 8080) print(f"Agent URL: {service.url}") # 3. Enable wake-on-request self.instance.set_wake_on( wake_on_http=True, wake_on_ssh=True ) print("Wake-on-request enabled for HTTP and SSH") return service.url def refresh_ttl(self): """Refresh TTL to keep instance warm during activity.""" if self.instance: self.instance.set_ttl( ttl_seconds=self.ttl_seconds, ttl_action="pause" ) # Usage agent = AutoScalingAgent("snapshot_your_snapshot_id", ttl_minutes=15) agent_url = agent.start() # In your request handler, refresh TTL on each interaction: # agent.refresh_ttl() ``` -------------------------------- ### Verify State Preservation of Counter (Bash) Source: https://cloud.morph.so/docs/developers This bash script verifies state preservation by checking the counter file in a new instance. It executes commands to read the counter, waits, and then reads it again to confirm the process continued. ```bash # Check counter in new instance NEW_COUNTER=$(morphcloud instance exec $NEW_INSTANCE "cat /root/counter.txt") echo "Counter in new instance: $NEW_COUNTER" # Wait to verify counter continues incrementing echo "Waiting to verify counter continues in new instance..." sleep 10 FINAL_COUNTER=$(morphcloud instance exec $NEW_INSTANCE "cat /root/counter.txt") echo "Counter after waiting in new instance: $FINAL_COUNTER" echo -e "\n✨ Success! The background process continued exactly where it left off." echo "Original instance counter: $INCREMENTED_COUNTER → New instance counter: $FINAL_COUNTER" ``` -------------------------------- ### Start Auto-Scaling Agent Workspace (TypeScript) Source: https://cloud.morph.so/docs/examples/auto-scale-agent-workspaces This TypeScript code demonstrates how to start an auto-scaling agent workspace. It initializes a MorphCloudClient, starts an instance with a specified Time-To-Live (TTL), exposes an HTTP service for the agent, and enables wake-on-request for HTTP and SSH. ```TypeScript import { MorphCloudClient, Instance } from 'morphcloud'; class AutoScalingAgent { private client: MorphCloudClient; private snapshotId: string; private ttlSeconds: number; private instance?: Instance; constructor(snapshotId: string, ttlMinutes: number = 15) { this.client = new MorphCloudClient({ apiKey: process.env.MORPH_API_KEY }); this.snapshotId = snapshotId; this.ttlSeconds = ttlMinutes * 60; } async start(): Promise { // 1. Start instance with TTL this.instance = await this.client.instances.start({ snapshotId: this.snapshotId, ttlSeconds: this.ttlSeconds, ttlAction: "pause" }); console.log(`Instance started: ${this.instance.id}`); // 2. Expose HTTP service (agent on port 8080) const service = await this.instance.exposeHttpService("agent", 8080); console.log(`Agent URL: ${service.url}`); // 3. Enable wake-on-request await this.instance.setWakeOn({ wakeOnHttp: true, wakeOnSsh: true }); console.log("Wake-on-request enabled for HTTP and SSH"); return service.url; } async refreshTTL(): Promise { if (this.instance) { await this.instance.setTtl({ ttlSeconds: this.ttlSeconds, ttlAction: "pause" }); } } } // Usage const agent = new AutoScalingAgent("snapshot_your_snapshot_id", 15); const agentUrl = await agent.start(); // In your request handler, refresh TTL on each interaction: // await agent.refreshTTL(); ``` -------------------------------- ### Install Morph Cloud SDK Source: https://cloud.morph.so/docs/examples/remote-desktop Installs the Morph Python SDK using uv pip. This is a prerequisite for interacting with the Morph Cloud services. ```bash uv pip install morphcloud ``` -------------------------------- ### Install Morph Cloud SDK (Python) Source: https://cloud.morph.so/docs/examples/browser-automation Installs the Morph Cloud Python SDK using uv pip. This is a prerequisite for using Morph Cloud services. ```bash uv pip install morphcloud ``` -------------------------------- ### Run Hello World with Morph Cloud (TypeScript) Source: https://cloud.morph.so/docs/documentation/setup/hello-world This TypeScript example shows how to create a Morph Cloud snapshot, launch an instance, execute a 'Hello World' command, and terminate the instance. It uses the MorphCloudClient asynchronously to manage cloud resources. ```TypeScript import { MorphCloudClient } from 'morphcloud'; async function helloWorld() { // Initialize client const client = new MorphCloudClient(); // 1. Create a new snapshot (or list existing ones) const newSnapshot = await client.snapshots.create({ image_id: "morphvm-minimal", vcpus: 1, memory: 1024, // MB disk_size: 10000 // MB }); console.log(`Created snapshot: ${newSnapshot.id}`); // 2. Start an instance from the snapshot const instance = await client.instances.start({ snapshot_id: newSnapshot.id }); console.log(`Started instance: ${instance.id}`); // Wait for instance to be ready await instance.waitUntilReady(); // 3. Run a hello world command const result = await instance.exec("echo 'Hello, Morph Cloud!'"); console.log(`Command output: ${result.stdout}`); // 4. Stop the instance when done await instance.stop(); console.log("Instance stopped"); } helloWorld().catch(console.error); ```