### Python Quickstart: Create, Execute, and Terminate Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandboxes/getting-started.mdx This Python code demonstrates the basic workflow of creating a sandbox, executing a command, retrieving logs, and terminating the sandbox. Ensure the SDK is installed. ```python from porter_sandbox import Porter with Porter() as porter: sandbox = porter.sandboxes.create( image="python:3.12-slim", name="getting-started-python", tags={"example": "getting-started"}, ) result = sandbox.exec(["python", "-c", "print(2 + 2)"]) print(result.stdout) logs = sandbox.logs(limit=100) print(logs) sandbox.terminate() ``` -------------------------------- ### TypeScript Quickstart: Create, Execute, and Terminate Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandboxes/getting-started.mdx This TypeScript code demonstrates the basic workflow of creating a sandbox, executing a command, retrieving logs, and terminating the sandbox. Ensure the SDK is installed. ```typescript import { Porter } from "porter-sandbox"; const porter = new Porter(); const sandbox = await porter.sandboxes.create({ image: "python:3.12-slim", name: "getting-started-typescript", tags: { example: "getting-started" }, }); const result = await sandbox.exec(["python", "-c", "print(2 + 2)"]); console.log(result.stdout); const logs = await sandbox.logs({ limit: 100 }); console.log(logs); await sandbox.terminate(); porter.close(); ``` -------------------------------- ### Download Azure Setup Script Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Download the script to automate Azure service principal creation. Ensure you have the Azure CLI installed and authenticated. ```bash # Download the setup script curl -O https://raw.githubusercontent.com/porter-dev/docs/main/scripts/setup-azure-porter.sh ``` -------------------------------- ### Install NGINX Ingress Controller Source: https://github.com/porter-dev/docs/blob/main/addons/custom-helm-charts.mdx Example of adding the ingress-nginx repository and installing the ingress-nginx chart. It creates the namespace if it doesn't exist. ```bash # Add the ingress-nginx repository porter helm -- repo add ingress-nginx https://kubernetes.github.io/ingress-nginx porter helm -- repo update # Install the chart porter helm -- install my-ingress ingress-nginx/ingress-nginx \ --namespace ingress \ --create-namespace ``` -------------------------------- ### Make Azure Setup Script Executable Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Make the downloaded Azure setup script executable. This allows you to run it for automating Azure service principal setup. ```bash # Make it executable chmod +x setup-azure-porter.sh ``` -------------------------------- ### Minimal porter.yaml configuration Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/overview.mdx A basic `porter.yaml` file to get started. Define the application name, services, and build method. ```yaml version: v2 name: my-app services: - name: web type: web run: npm start port: 3000 cpuCores: 0.5 ramMegabytes: 512 build: method: docker context: . dockerfile: ./Dockerfile ``` -------------------------------- ### Complete Application Configuration Example Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/reference.mdx A comprehensive example demonstrating various configuration options for an application, including build, environment, services, and advanced settings like autoscaling and GPU usage. ```yaml version: v2 name: my-app build: method: docker context: . dockerfile: ./Dockerfile env: PORT: "8080" LOG_LEVEL: "info" envGroups: - production-secrets - shared-config predeploy: run: python manage.py migrate cpuCores: 0.5 ramMegabytes: 512 initialDeploy: run: python manage.py seed cpuCores: 0.25 ramMegabytes: 256 autoRollback: enabled: true efsStorage: enabled: true services: # Web service with all options - name: web type: web run: python app.py instances: 2 cpuCores: 1 ramMegabytes: 1024 port: 8080 terminationGracePeriodSeconds: 30 autoscaling: enabled: true minInstances: 2 maxInstances: 10 cpuThresholdPercent: 80 memoryThresholdPercent: 80 healthCheck: enabled: true httpPath: /healthz domains: - name: app.example.com metricsScraping: enabled: true path: /metrics port: 9090 scrapeIntervalSeconds: 30 connections: - type: awsRole role: my-app-role # GPU-enabled worker on a custom node group - name: ml-worker type: worker run: python ml_worker.py instances: 1 cpuCores: 4 ramMegabytes: 16384 gpuCoresNvidia: 1 nodeGroup: 123e4567-e89b-12d3-a456-426614174000 terminationGracePeriodSeconds: 60 serviceMeshEnabled: true # Background worker - name: worker type: worker run: python worker.py instances: 1 cpuCores: 0.5 ramMegabytes: 512 # Scheduled job - name: cleanup type: job run: python cleanup.py cpuCores: 0.5 ramMegabytes: 256 cron: "0 0 * * *" ``` -------------------------------- ### Install application dependencies Source: https://github.com/porter-dev/docs/blob/main/quickstart/python/fastapi.mdx Run this command in your terminal to install all the dependencies listed in your requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/porter-dev/docs/blob/main/README.md Install the Mintlify CLI globally to preview documentation changes locally. This command is run using npm. ```bash npm i mintlify -g ``` -------------------------------- ### Run Azure Setup Script Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Execute the Azure setup script to create the necessary roles, service principal, and grant permissions. Optionally provide your subscription ID. ```bash # Run the script (optionally provide subscription ID) ./setup-azure-porter.sh [your-subscription-id] ``` -------------------------------- ### Service Start Commands Source: https://github.com/porter-dev/docs/blob/main/applications/deploy/configuring-application-services.mdx Different services can run the same image with different start commands. Use these to specify the process for each service type. ```bash npm start ``` ```bash npm run worker ``` ```bash npm run cleanup ``` -------------------------------- ### Complete Web Service Configuration Example Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/services/web-service.mdx A comprehensive example demonstrating the configuration of a web service, including autoscaling, custom domains, health checks, path routing, ingress annotations, metrics scraping, cloud connections, and graceful shutdown. ```yaml services: - name: api type: web run: npm start port: 8080 cpuCores: 1 ramMegabytes: 1024 # Autoscaling autoscaling: enabled: true minInstances: 1 maxInstances: 10 cpuThresholdPercent: 80 memoryThresholdPercent: 80 # Custom domains domains: - name: example.com # Health checks livenessCheck: enabled: true httpPath: /livez timeoutSeconds: 1 initialDelaySeconds: 15 readinessCheck: enabled: true httpPath: /readyz timeoutSeconds: 1 initialDelaySeconds: 15 # Path routing pathRouting: - path: /api/v1/ port: 8080 - path: /api/v2/ port: 8081 pathRoutingConfig: rewriteMode: rewrite-prefix # Ingress configuration ingressAnnotations: nginx.ingress.kubernetes.io/proxy-connect-timeout: "18000" # Service mesh and metrics serviceMeshEnabled: true metricsScraping: enabled: true path: /metrics port: 9090 scrapeIntervalSeconds: 60 # Cloud connections connections: - type: awsRole role: api-s3-access # Graceful shutdown terminationGracePeriodSeconds: 30 ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/porter-dev/docs/blob/main/README.md Start the Mintlify development server from the root of your documentation directory. Ensure mint.json is present. ```bash mintlify dev ``` -------------------------------- ### Start the Next.js application locally Source: https://github.com/porter-dev/docs/blob/main/quickstart/javascript/nextjs.mdx Execute `npm run start` to run your Next.js application locally, verifying its functionality before deployment. ```bash npm run start ``` -------------------------------- ### Complete Job Service Example Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/services/job-service.mdx A comprehensive example of a job service configuration in `porter.yaml`, demonstrating scheduling, timeouts, concurrency, connections, and graceful shutdown. ```yaml services: - name: daily-report type: job run: python generate_report.py cpuCores: 1 ramMegabytes: 2048 # Schedule: Daily at 6 AM UTC cron: "0 6 * * *" # Allow up to 2 hours timeoutSeconds: 7200 # Don't allow concurrent runs allowConcurrent: false # Cloud connections connections: - type: awsRole role: report-s3-access # Graceful shutdown terminationGracePeriodSeconds: 60 ``` -------------------------------- ### Example Procfile Source: https://github.com/porter-dev/docs/blob/main/other/migrate-from-heroku.mdx An example of a Heroku Procfile defining different application processes and their commands. ```yaml web: puma worker: sidekiq-process-manager release: bundle exec rake db:migrate ``` -------------------------------- ### Verify start command using jq Source: https://github.com/porter-dev/docs/blob/main/quickstart/javascript/nextjs.mdx Confirm the `scripts.start` command in `package.json` has been updated correctly using `jq`. ```bash jq '.scripts.start' package.json ``` -------------------------------- ### Create a basic FastAPI application Source: https://github.com/porter-dev/docs/blob/main/quickstart/python/fastapi.mdx This is a simple 'Hello World' example for a FastAPI application. Ensure this code is saved in a main.py file. ```python from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} ``` -------------------------------- ### Example comprehensive porter.yaml Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/overview.mdx An example `porter.yaml` file demonstrating various configurations for web, worker, and job services, including autoscaling, health checks, cron jobs, build settings, environment variables, and environment groups. ```yaml version: v2 name: my-app services: - name: api type: web run: node index.js port: 8080 cpuCores: 0.1 ramMegabytes: 256 autoscaling: enabled: true minInstances: 1 maxInstances: 3 memoryThresholdPercent: 60 cpuThresholdPercent: 60 private: false domains: - name: test1.example.com healthCheck: enabled: true httpPath: /healthz - name: example-wkr type: worker run: echo 'work' port: 8081 cpuCores: 0.1 ramMegabytes: 256 instances: 1 - name: example-job type: job run: echo 'hello world' allowConcurrent: true cpuCores: 0.1 ramMegabytes: 256 cron: '*/10 * * * *' predeploy: run: ls build: method: docker context: ./ dockerfile: ./app/Dockerfile env: NODE_ENV: production envGroups: - production-env-group ``` -------------------------------- ### Automated Azure Service Principal Setup Source: https://github.com/porter-dev/docs/blob/main/cloud-accounts/connecting-a-cloud-account.mdx Use this script to automate the creation of an Azure service principal for Porter. Ensure you have the Azure CLI installed and are logged in. ```bash # Download the setup script curl -O https://raw.githubusercontent.com/porter-dev/docs/main/scripts/setup-azure-porter.sh # Make it executable chmod +x setup-azure-porter.sh # Run the script (optionally provide subscription ID) ./setup-azure-porter.sh [your-subscription-id] ``` -------------------------------- ### Install a Helm Chart Source: https://github.com/porter-dev/docs/blob/main/addons/custom-helm-charts.mdx Install a Helm chart from a repository. Specify the release name, chart, namespace, and optionally a values file. The `--create-namespace` flag can be used if the namespace does not exist. ```bash porter helm -- install / \ --namespace \ --values values.yaml ``` -------------------------------- ### Verify Porter CLI Installation Source: https://github.com/porter-dev/docs/blob/main/cli/installation.mdx Run this command after installation to confirm that the Porter CLI is installed correctly and to check its version. ```bash porter version ``` -------------------------------- ### Install the SDK Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/quickstart.mdx Add the porter-sandbox SDK to your application using npm. ```bash npm install porter-sandbox ``` -------------------------------- ### Async usage: Create and mount a volume Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/volumes.mdx Asynchronously create a volume and mount it into a sandbox. This example demonstrates the async interface for managing volumes and sandboxes. ```python from porter_sandbox import AsyncPorter async with AsyncPorter() as porter: volume = await porter.volumes.create(name="async-workspace") sandbox = await porter.sandboxes.create( image="python:3.12-slim", volume_mounts={"/workspace": volume.id}, ) try: result = await sandbox.exec(["sh", "-lc", "echo hello > /workspace/out.txt && cat /workspace/out.txt"]) print(result.stdout) finally: await sandbox.terminate() ``` -------------------------------- ### Start Document Processing Workflow Source: https://github.com/porter-dev/docs/blob/main/applications/configure/temporal-autoscaling.mdx Starts a Temporal workflow for each uploaded document. Ensure the Temporal client is initialized. ```python from temporalio.client import Client @app.post("/upload") async def upload_document(file: UploadFile): # Start a Temporal workflow for each uploaded document await temporal_client.start_workflow( ProcessDocumentWorkflow.run, args=[file.filename], id=f"doc-{uuid4()}", task_queue="document-processing" ) return {"status": "processing"} ``` -------------------------------- ### Install Application Dependencies Source: https://github.com/porter-dev/docs/blob/main/quickstart/ruby/rails.mdx Install all the necessary Ruby gems for your Rails application. Run this command in the application's root directory. ```bash bundle install ``` -------------------------------- ### Install Python Sandbox SDK Source: https://github.com/porter-dev/docs/blob/main/sandboxes/getting-started.mdx Install the Python Sandbox SDK using pip. This is required before you can use the SDK in your Python application. ```bash pip install porter-sandbox ``` -------------------------------- ### Create a New App Source: https://github.com/porter-dev/docs/blob/main/standard/cli/command-reference/porter-app.mdx Creates and deploys a new application in your project. If no flags are specified, interactive prompts will guide the configuration. ```bash porter app create ``` ```bash porter app create --name example-app ``` ```bash porter app create --name my-app -f porter.yaml ``` -------------------------------- ### Configure Next.js start command for Porter Source: https://github.com/porter-dev/docs/blob/main/quickstart/javascript/nextjs.mdx Update the `scripts.start` command in `package.json` to `next start --hostname=0.0.0.0` to ensure Porter can route traffic correctly. ```json { "scripts": { "start": "next start --hostname=0.0.0.0" } } ``` -------------------------------- ### Install Helm Chart with Version Pinning Source: https://github.com/porter-dev/docs/blob/main/addons/custom-helm-charts.mdx Install a Helm chart and pin it to a specific version for reproducible deployments. This is a best practice to ensure consistency. ```bash porter helm -- install my-release repo/chart --version 1.2.3 ``` -------------------------------- ### Configure Pre-deployment Job Command Source: https://github.com/porter-dev/docs/blob/main/applications/deploy/configuring-application-services.mdx Set a start command for pre-deployment jobs, such as database migrations. Ensure the command is configured to run within the allocated resources and timeout. ```bash npm run migrate ``` ```bash python manage.py migrate ``` ```bash bundle exec rails db:migrate ``` -------------------------------- ### Database Cleanup Job Example Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/services/job-service.mdx An example of a job service configured for database cleanup, including cron schedule, timeout, and concurrency settings. ```yaml services: - name: db-cleanup type: job run: npm run cleanup-old-records cpuCores: 0.25 ramMegabytes: 256 cron: "0 3 * * *" # 3 AM daily timeoutSeconds: 1800 allowConcurrent: false ``` -------------------------------- ### Install Helm Chart using Version Control Values Source: https://github.com/porter-dev/docs/blob/main/addons/custom-helm-charts.mdx Install a Helm chart using values and version information stored in version-controlled files. This approach is useful for CI/CD pipelines. ```bash CHART_URL=$(yq e '.chartUrl' porter-custom-helm-chart-addons/custom-chart/chart.yaml) VERSION=$(yq e '.version' porter-custom-helm-chart-addons/custom-chart/chart.yaml) porter helm -- install custom-chart $CHART_URL \ --version $VERSION \ --values porter-custom-helm-chart-addons/custom-chart/values.yaml ``` -------------------------------- ### Minimal porter.yaml Example Source: https://github.com/porter-dev/docs/blob/main/standard/cli/command-reference/porter-apply.mdx A basic `porter.yaml` file defining an application with a single web service. ```yaml version: v2 name: my-app services: - name: web type: web run: npm start port: 3000 cpuCores: 0.5 ramMegabytes: 512 ``` -------------------------------- ### GitHub Actions Workflow for Deployment Source: https://github.com/porter-dev/docs/blob/main/standard/cli/command-reference/porter-apply.mdx Example GitHub Actions workflow that checks out code, sets up Porter, and deploys the application using `porter apply` with necessary environment variables. ```yaml name: Deploy to my-app on: push: branches: - main jobs: porter-deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Set Github tag id: vars run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - name: Setup porter uses: porter-dev/setup-porter@v0.1.0 - name: Deploy stack run: porter apply timeout-minutes: 30 env: PORTER_CLUSTER: "1" PORTER_HOST: https://dashboard.porter.run PORTER_PROJECT: "1" PORTER_TOKEN: ${{ secrets.PORTER_TOKEN }} PORTER_TAG: ${{ steps.vars.outputs.sha_short }} PORTER_APP_NAME: my-app PORTER_DEPLOYMENT_TARGET_ID: your-deployment-target-id ``` -------------------------------- ### Update start command using jq Source: https://github.com/porter-dev/docs/blob/main/quickstart/javascript/nextjs.mdx Modify the `scripts.start` command in `package.json` programmatically using `jq`. ```bash content="$(jq --arg var "next start --hostname=0.0.0.0" '.scripts.start = $var' package.json)" echo "$content" >package.json ``` -------------------------------- ### Dockerfile Build with Build-time Environment Variable Source: https://github.com/porter-dev/docs/blob/main/applications/deploy/builds.mdx Example snippet from a Dockerfile demonstrating how to use build-time environment variables. The `ARG` keyword makes the variable available during the build, and `${env-var-name}` syntax references it. ```dockerfile ... ARG PORTER_ENV_VARIABLE RUN echo "Here is my env variable: ${PORTER_ENV_VARIABLE}" ... ``` -------------------------------- ### Prometheus Client Library Example Source: https://github.com/porter-dev/docs/blob/main/applications/observability/custom-metrics-and-autoscaling.mdx This Python snippet shows how to import necessary Prometheus client libraries for exposing metrics. This is a starting point for instrumenting your application to generate metrics that Porter can scrape. ```python from prometheus_client import generate_latest, Gauge ``` -------------------------------- ### Create a Volume and Mount Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/reference.mdx Create a persistent volume and then create a sandbox that mounts this volume at a specified path. ```python volume = porter.volumes.create(name="my-data") sandbox = porter.sandboxes.create( image="python:3.12-slim", volume_mounts={"/mnt/data": volume.id}, ) ``` -------------------------------- ### Install Porter CLI on macOS/Linux via Shell Script Source: https://github.com/porter-dev/docs/blob/main/cli/installation.mdx Install the Porter CLI on macOS or Linux by executing a shell script downloaded via curl. Ensure you have `curl` and `unzip` installed. ```bash /bin/bash -c "$(curl -fsSL https://install.porter.run)" ``` -------------------------------- ### Viewing Help Instructions Source: https://github.com/porter-dev/docs/blob/main/cli/basic-usage.mdx Demonstrates how to view general help, command help, and subcommand help using the `-h` or `--help` flags. ```bash # General help poter -h # Help for a specific command poter app -h # Help for a subcommand poter app run -h ``` -------------------------------- ### Install Rails Gem Source: https://github.com/porter-dev/docs/blob/main/quickstart/ruby/rails.mdx Install the Rails gem to scaffold a new Rails application. This is a prerequisite for creating a new Rails project. ```bash gem install rails ``` -------------------------------- ### Install Porter CLI on macOS via Homebrew Source: https://github.com/porter-dev/docs/blob/main/cli/installation.mdx Use this command to install the Porter CLI on macOS using the Homebrew package manager. ```bash brew install porter-dev/porter/porter ``` -------------------------------- ### Configure Worker Start Command Source: https://github.com/porter-dev/docs/blob/main/applications/deploy/configuring-application-services.mdx Define the start command for worker services that run continuously to process tasks or handle background work. ```bash python worker.py ``` ```bash node src/consumer.js ``` -------------------------------- ### Sandboxes: Create Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/reference.mdx Create a new sandbox with specified configuration, including image, name, environment variables, and volume mounts. ```APIDOC ## `porter.sandboxes.create` ```typescript const sandbox = await porter.sandboxes.create({ image: "python:3.12-slim", name: "my-sandbox", command: undefined, args: undefined, env: undefined, tags: { workflow: "demo" }, volume_mounts: undefined, }); ``` ### Options | Option | Type | Description | | ------ | ---- | ----------- | | `image` | `string` | Container image to run. | | `name` | `string | undefined` | Optional cluster-unique sandbox name. Use lowercase letters, numbers, and hyphens; start and end with a letter or number. Names currently cannot be reused, even after termination. | | `command` | `string[] | undefined` | Optional entrypoint override. | | `args` | `string[] | undefined` | Optional arguments passed to the command. | | `env` | `Record | undefined` | Environment variables to set in the sandbox. | | `tags` | `Record | undefined` | Key-value labels for finding related sandboxes. | | `volume_mounts` | `Record | undefined` | Volume IDs keyed by absolute mount path inside the sandbox. | Returns a `Sandbox` handle. ``` -------------------------------- ### Prometheus Metrics Output Example Source: https://github.com/porter-dev/docs/blob/main/applications/observability/custom-metrics-and-autoscaling.mdx This is an example of how metrics should be formatted when exposed by an application. Ensure your application adheres to this format for Porter to scrape and use the metrics. ```prometheus # HELP http_requests_total Total number of HTTP requests # TYPE http_requests_total counter http_requests_total{method="post",code="200"} 1027 http_requests_total{method="get",code="200"} 2048 ``` -------------------------------- ### Basic porter.yaml Configuration Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Create a `porter.yaml` file to define your application's name, build method, and services. This is the simplest configuration for deploying an application. ```yaml version: v2 name: my-app build: method: docker dockerfile: ./Dockerfile services: - name: web type: web run: npm start port: 3000 cpuCores: 0.5 ramMegabytes: 512 ``` -------------------------------- ### Async Sandbox Creation and Execution Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/quickstart.mdx Demonstrates asynchronous creation of a sandbox, execution of a command, and subsequent termination using `AsyncPorter`. This pattern is suitable for non-blocking operations in async applications. ```python import asyncio from porter_sandbox import AsyncPorter async def main(): async with AsyncPorter() as porter: sandbox = await porter.sandboxes.create( image="python:3.12-slim", name="async-python-demo", ) try: result = await sandbox.exec(["python", "-c", "print(2 + 2)"]) print(result.stdout) finally: await sandbox.terminate() asyncio.run(main()) ``` -------------------------------- ### Create a Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/reference.mdx Create a new sandbox with specified image and name. Optional arguments include command, environment variables, tags, and volume mounts. ```python sandbox = porter.sandboxes.create( image="python:3.12-slim", name="my-sandbox", command=None, args=None, env=None, tags={"workflow": "demo"}, volume_mounts=None, ) ``` -------------------------------- ### Complete Worker Service Example Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/services/worker-service.mdx A comprehensive example of a worker service configuration, including autoscaling, health checks, cloud connections, service mesh integration, and graceful shutdown. ```yaml services: - name: queue-processor type: worker run: npm run worker cpuCores: 1 ramMegabytes: 2048 # Autoscaling autoscaling: enabled: true minInstances: 2 maxInstances: 20 cpuThresholdPercent: 70 memoryThresholdPercent: 80 # Health checks livenessCheck: enabled: true command: ./healthcheck.sh timeoutSeconds: 5 readinessCheck: enabled: true command: ./ready.sh timeoutSeconds: 3 # Cloud connections connections: - type: awsRole role: worker-sqs-access # Service mesh serviceMeshEnabled: true # Graceful shutdown (allow 2 minutes for jobs to complete) terminationGracePeriodSeconds: 120 ``` -------------------------------- ### Fetch Logs from a Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/quickstart.mdx Create a sandbox, execute a command that produces output, and then fetch and print the logs from the sandbox. Ensure the sandbox is terminated in a finally block. ```python from porter_sandbox import Porter with Porter() as porter: sandbox = porter.sandboxes.create( image="python:3.12-slim", name="python-logs-demo", ) try: sandbox.exec(["python", "-c", "print('log me')"]) for line in sandbox.logs(limit=100): print(f"{line.timestamp} [{line.level}] {line.line}") finally: sandbox.terminate() ``` -------------------------------- ### Check command path and PATH variable Source: https://github.com/porter-dev/docs/blob/main/applications/debug/common-errors.mdx Use this command to verify the location of your start command and inspect the container's PATH environment variable. This is useful when debugging start command issues. ```bash $ which $ echo $PATH ``` -------------------------------- ### List Deployment Targets Source: https://github.com/porter-dev/docs/blob/main/standard/cli/command-reference/porter-target.mdx Lists all deployment targets in the current cluster. Use the `--preview` flag to include targets for preview environments. ```bash porter target list ``` ```bash porter target list --preview ``` -------------------------------- ### Initialize Sync Porter Client Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/reference.mdx Instantiate the synchronous Porter client. Use a 'with' statement for automatic resource management. ```python from porter_sandbox import Porter with Porter() as porter: sandbox = porter.sandboxes.create( image="python:3.12-slim", name="my-sandbox", ) ``` -------------------------------- ### Create, Execute, and Terminate a Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/quickstart.mdx Create a sandbox with a specified image and name, execute a command, print its standard output, and then terminate the sandbox. This is the basic workflow for running a task in a sandbox. ```python from porter_sandbox import Porter with Porter() as porter: sandbox = porter.sandboxes.create( image="python:3.12-slim", name="python-quickstart", tags={"example": "python-quickstart"}, ) result = sandbox.exec(["python", "-c", "print('hello from porter')"]) print(result.stdout) sandbox.terminate() ``` -------------------------------- ### Volumes: Get Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/reference.mdx Retrieve a specific volume by its name. ```APIDOC ## `porter.volumes.get(name)` Fetches a volume by name. ``` -------------------------------- ### Deploy Application with `porter apply` Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Build and deploy your application using the `porter apply` command with a specified `porter.yaml` file. This command handles both building the container image and deploying it to your cluster. ```bash porter apply -f porter.yaml ``` -------------------------------- ### Sandboxes: Get Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/reference.mdx Retrieve a sandbox handle by its name. ```APIDOC ## `porter.sandboxes.get` ```typescript const sandbox = await porter.sandboxes.get("my-sandbox"); ``` Looks up a sandbox by name and returns a `Sandbox` handle. Use names as the canonical reference for sandboxes you need to operate on later. ``` -------------------------------- ### Valid PromQL Query Examples Source: https://github.com/porter-dev/docs/blob/main/applications/observability/custom-metrics-and-autoscaling.mdx These examples demonstrate valid PromQL queries that return a single numeric value, suitable for custom autoscaling thresholds. Ensure your queries use aggregation operators if they might otherwise return multiple time series. ```promql avg(metric_name) ``` ```promql sum(rate(http_requests_total[5m])) ``` ```promql max(queue_length) ``` -------------------------------- ### List All Applications Source: https://github.com/porter-dev/docs/blob/main/standard/cli/command-reference/porter-app.mdx Lists all applications currently defined within the Porter project. ```bash porter app list ``` -------------------------------- ### Create and mount a volume Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/volumes.mdx Create a new volume and mount it into a sandbox. Ensure any sandboxes using the volume are terminated before attempting to delete the volume. ```python from porter_sandbox import Porter with Porter() as porter: volume = porter.volumes.create(name="agent-workspace") sandbox = porter.sandboxes.create( image="python:3.12-slim", volume_mounts={"/workspace": volume.id}, ) try: sandbox.exec(["python", "-c", "open('/workspace/result.txt', 'w').write('done')"]) result = sandbox.exec(["cat", "/workspace/result.txt"]) print(result.stdout) finally: sandbox.terminate() ``` -------------------------------- ### Get a Volume by Name Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/volumes.mdx Retrieves a specific persistent volume by its unique name. ```APIDOC ## Get Volume by Name ### Description Retrieves a specific persistent volume by its name. Volume names are unique within the cluster. ### Method `porter.volumes.get(name: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - The name of the volume to retrieve. ### Request Example ```typescript const volume = await porter.volumes.get("agent-workspace"); ``` ### Response #### Success Response - **id** (string) - The unique identifier of the volume. - **name** (string) - The name of the volume. - **phase** (string) - The current phase of the volume. - **attached_to** (string | null) - The ID of the sandbox the volume is attached to, or null if not attached. #### Response Example ```json { "id": "vol-12345", "name": "agent-workspace", "phase": "Bound", "attached_to": null } ``` ``` -------------------------------- ### List Available Projects Source: https://github.com/porter-dev/docs/blob/main/cli/basic-usage.mdx Lists all available projects that the authenticated user has access to. ```bash porter projects list ``` -------------------------------- ### Get Azure Egress IPs using Azure CLI Source: https://github.com/porter-dev/docs/blob/main/security-and-compliance/static-egress-ip.mdx This two-step process retrieves your Azure Kubernetes Service (AKS) cluster's egress IP. The first command gets the ID of the outbound IP configuration, and the second command uses that ID to fetch the actual IP address. Ensure you replace `` and ``. ```bash az aks show -g -n --query 'networkProfile.loadBalancerProfile.effectiveOutboundIPs[].id' ``` ```bash az network public-ip show --ids --query ipAddress -o tsv ``` -------------------------------- ### Create Sandbox with Volume Mount Source: https://github.com/porter-dev/docs/blob/main/sandboxes/cli.mdx Creates a sandbox with a volume mounted. The volume mount is specified in `mount_path=volume-ref` format, where `volume-ref` can be a volume name or ID. The mount path must be absolute. ```bash porter sandbox create ubuntu:24.04 --volume /workspace=my-data -- bash -lc 'ls -la /workspace' ``` -------------------------------- ### Create Sandbox with Environment Variables and Tags Source: https://github.com/porter-dev/docs/blob/main/sandboxes/cli.mdx Creates a sandbox and configures environment variables and tags. Environment variables are passed in `KEY=VALUE` format, and tags are in `key=value` format. These can be repeated. ```bash porter sandbox create ghcr.io/example/tool:latest --env PORT=8080 --tag env=dev --tag owner=me ``` -------------------------------- ### Get a Sandbox by Name Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/reference.mdx Retrieve a sandbox handle by its name. This is useful for operating on existing sandboxes. ```typescript const sandbox = await porter.sandboxes.get("my-sandbox"); ``` -------------------------------- ### Create a Volume and Mount it to a Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/reference.mdx Create a named volume and then create a sandbox, mounting the volume into the sandbox's filesystem. ```typescript const volume = await porter.volumes.create({ name: "my-data" }); const sandbox = await porter.sandboxes.create({ image: "python:3.12-slim", volume_mounts: { "/mnt/data": volume.id }, }); ``` -------------------------------- ### Get a Sandbox Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/python/reference.mdx Retrieve a sandbox handle by its unique name. This is useful for operating on existing sandboxes. ```python sandbox = porter.sandboxes.get("my-sandbox") ``` -------------------------------- ### Fetch Sandbox Logs Source: https://github.com/porter-dev/docs/blob/main/sandbox/sdk/typescript/quickstart.mdx Create a sandbox, execute a command that produces output, fetch the logs, and then terminate the sandbox. Logs are returned as structured log lines. ```typescript import { Porter } from "porter-sandbox"; const porter = new Porter(); const sandbox = await porter.sandboxes.create({ image: "python:3.12-slim", name: "typescript-logs-demo", }); try { await sandbox.exec(["python", "-c", "print('log me')"]); const logs = await sandbox.logs({ limit: 100 }); for (const line of logs) { console.log(`${line.timestamp} [${line.level}] ${line.line}`); } } finally { await sandbox.terminate(); porter.close(); } ``` -------------------------------- ### Deploy application with preview environment Source: https://github.com/porter-dev/docs/blob/main/applications/configuration-as-code/overview.mdx Use this command to spin up isolated preview environments for pull requests, ensuring consistent configuration. Requires `porter.yaml`. ```bash porter apply -f porter.yaml --preview ``` -------------------------------- ### Login and Configure Porter CLI Source: https://github.com/porter-dev/docs/blob/main/getting-started/quickstart.mdx Authenticate with Porter and set up your default project and cluster. This command opens a browser for authentication and automatically configures the CLI. ```bash porter auth login ``` -------------------------------- ### Get JSON Output of Sandboxes Source: https://github.com/porter-dev/docs/blob/main/sandboxes/cli.mdx Retrieves a JSON array of all sandboxes, which is recommended for scripting and automated processing. ```bash porter sandbox list -o json ``` -------------------------------- ### Create and Mount a Volume Source: https://github.com/porter-dev/docs/blob/main/sandboxes/cli.mdx Creates a named volume and then creates a sandbox, mounting the volume to a specified path. This allows for persistent storage across sandbox lifecycles. ```bash porter sandbox volume create my-data && porter sandbox create ubuntu:24.04 --volume /workspace=my-data -- bash ``` -------------------------------- ### Run Rails Development Server Source: https://github.com/porter-dev/docs/blob/main/quickstart/ruby/rails.mdx Start the Rails development server locally. This command allows you to test your application before deploying. ```bash bin/rails server ``` -------------------------------- ### Connect to Datastore via Porter CLI Source: https://github.com/porter-dev/docs/blob/main/addons/datastores.mdx Use the Porter CLI to connect to a datastore from your local machine. This command requires Tailscale VPN if your cluster control plane access is private. ```bash porter datastore connect my-datastore psql -h localhost -p -U -l ```