### Example: Installing Dev Container Features with features Source: https://containers.dev/implementors/json_reference Provides an example of how to include and configure Dev Container Features within your development environment using the `features` property. Specific options depend on the feature being installed. ```json { "features": { "ghcr.io/devcontainers/features/github-cli": {} } } ``` -------------------------------- ### Start a Dev Container with Rust Sample using CLI Source: https://containers.dev/implementors/reference This snippet demonstrates how to clone a Rust sample project and start a development container using the Dev Containers CLI's `up` command. It downloads the container image and launches the Rust environment. ```bash git clone https://github.com/microsoft/vscode-remote-try-rust devcontainer up --workspace-folder ``` -------------------------------- ### Example: Overriding Feature Install Order Source: https://containers.dev/implementors/json_reference Demonstrates how to manually specify the installation order of Dev Container Features using the `overrideFeatureInstallOrder` property. This is useful when feature dependencies require a specific installation sequence. ```json { "overrideFeatureInstallOrder": [ "ghcr.io/devcontainers/features/common-utils", "ghcr.io/devcontainers/features/github-cli" ] } ``` -------------------------------- ### Example: Setting Security Options with securityOpt Source: https://containers.dev/implementors/json_reference Illustrates setting container security options, such as disabling seccomp filtering, using the `securityOpt` property. This can be necessary for specific security configurations. ```json { "securityOpt": ["seccomp=unconfined"] } ``` -------------------------------- ### Example: Adding Capabilities with capAdd Source: https://containers.dev/implementors/json_reference Demonstrates how to add specific capabilities to a container using the `capAdd` property. This is often used to grant permissions like `ptrace` for debugging. ```json { "capAdd": ["SYS_PTRACE"] } ``` -------------------------------- ### Dev Container Feature Configuration Example Source: https://containers.dev/implementors/features An example of the 'features' object in a devcontainer.json file, demonstrating how to include various features with different referencing methods and options. It shows default options, version pinning, and local feature references. ```json { "features": { "ghcr.io/user/repo/go": {}, "ghcr.io/user/repo1/go:1": {}, "ghcr.io/user/repo2/go:latest": {}, "https://github.com/user/repo/releases/devcontainer-feature-go.tgz": { "optionA": "value" }, "./myGoFeature": { "optionA": true, "optionB": "hello", "version" : "1.0.0" } } } ``` -------------------------------- ### Dev Container Lifecycle Script Examples Source: https://containers.dev/implementors/json_reference Examples demonstrating the usage of dev container lifecycle scripts. These scripts can be defined as strings for shell execution or as arrays for direct command invocation. The examples show basic command execution and chaining. ```json { "initializeCommand": "echo 'Initializing container...'", "onCreateCommand": [ "apt-get update", "apt-get install -y git" ], "updateContentCommand": "bash scripts/update-content.sh", "postCreateCommand": "yarn install", "postStartCommand": "echo 'Container started.'", "postAttachCommand": "echo 'Attached to container.'" } ``` -------------------------------- ### Define Feature Installation Order with installsAfter Source: https://containers.dev/implementors/features This JSON snippet demonstrates how to use the 'installsAfter' property within a devcontainer.json configuration. It specifies that 'myFeature' should be installed after 'foo' and 'bar', but only if 'myFeature' is already queued for installation. This property acts as a soft dependency, influencing order without forcing installation. ```json { "name": "My Feature", "id": "myFeature", "version": "1.0.0", "installsAfter": [ "foo", "bar" ] } ``` -------------------------------- ### Dev Container Feature Mount Configuration Example Source: https://containers.dev/implementors/features An example snippet showing how a dev container feature might define volume mounts. This specific example uses a dynamic volume name based on the dev container ID, intended for features like Docker-in-Docker. ```json { "id": "docker-in-docker", "version": "1.0.4", // ... "mounts": [ { "source": "dind-var-lib-docker-${devcontainerId}", "target": "/var/lib/docker", "type": "volume" } ] } ``` -------------------------------- ### Example: Defining Custom Mounts with mounts Source: https://containers.dev/implementors/json_reference Shows how to define custom volume mounts for a container using the `mounts` property. This allows specifying source, target, and type for persistent storage or shared directories. ```json { "mounts": [ { "source": "dind-var-lib-docker", "target": "/var/lib/docker", "type": "volume" } ] } ``` -------------------------------- ### Define Post-Start Command (JSON) Source: https://containers.dev/implementors/json_schema Specifies a command to run after the container has started. This executes after 'postCreateCommand' and before 'postAttachCommand'. Supports string or array formats. ```json { "postStartCommand": "./start_services.sh" } ``` ```json { "postStartCommand": [ "systemctl", "start", "nginx" ] } ``` -------------------------------- ### Python Feature Options Resolution Example Source: https://containers.dev/implementors/features Demonstrates how options defined in a Feature's devcontainer-feature.json are resolved and exposed as environment variables to the install.sh script based on user configurations in devcontainer.json. ```json { "options": { "version": { "type": "string", "enum": ["latest", "3.10", "3.9", "3.8", "3.7", "3.6"], "default": "latest", "description": "Select a Python version to install." }, "pip": { "type": "boolean", "default": true, "description": "Installs pip" }, "optimize": { "type": "boolean", "default": true, "description": "Optimize python installation" } } } ``` ```json { "features": { "ghcr.io/devcontainers/features/python:1": { "version": "3.10", "pip": false } } } ``` ```shell #!/usr/bin/env bash echo "Version is $VERSION" echo "Pip? $PIP" echo "Optimize? $OPTIMIZE" ``` -------------------------------- ### Example overrideFeatureInstallOrder in devcontainer.json Source: https://containers.dev/implementors/features Illustrates how to use the `overrideFeatureInstallOrder` property within a `devcontainer.json` file. This property takes an array of Feature IDs to define their installation priority. The order specified is crucial and must be consistent with the resolved dependency graph. ```json { "name": "My Dev Container", "features": { "foo": {}, "bar": {}, "baz": {} }, "overrideFeatureInstallOrder": [ "foo", "bar", "baz" ] } ``` -------------------------------- ### Install Dev Container CLI using npm Source: https://containers.dev/implementors/reference Installs the Dev Container CLI globally using the npm package manager. This command requires Node.js (version 14 or greater), Python, and C/C++ to be installed on your system. ```bash npm install -g @devcontainers/cli ``` -------------------------------- ### Write Persistent Script in install.sh Source: https://containers.dev/implementors/features Demonstrates writing a shell script to a known, persistent path within the container during feature installation. This script can be executed later in lifecycle hooks. ```shell PULL_GIT_LFS_SCRIPT_PATH="/usr/local/share/pull-git-lfs-artifacts.sh" tee "$PULL_GIT_LFS_SCRIPT_PATH" > /dev/null \ << EOF #!/bin/sh set -e <...truncated...> EOF ``` -------------------------------- ### Dev Container Feature Version Shorthand Example Source: https://containers.dev/implementors/features Illustrates a shorthand notation for specifying a feature version in devcontainer.json. This is equivalent to explicitly defining the version within the feature's options object. ```json "features": { "ghcr.io/owner/repo/go": "1.18" } ``` ```json "features": { "ghcr.io/owner/repo/go": { "version": "1.18" } } ``` -------------------------------- ### Example OCI Manifest with Metadata Annotation (JSON) Source: https://containers.dev/implementors/features-distribution This JSON object represents an example OCI image manifest for a devcontainer Feature. It includes the schema version, media types for config and layers, digests, sizes, and importantly, the `dev.containers.metadata` annotation which contains the escaped JSON of the `devcontainer-feature.json`. ```json { "schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": { "mediaType": "application/vnd.devcontainers", "digest": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, "layers": [ { "mediaType": "application/vnd.devcontainers.layer.v1+tar", "digest": "sha256:738af5504b253dc6de51d2cb1556cdb7ce70ab18b2f32b0c2f12650ed6d2e4bc", "size": 3584, "annotations": { "org.opencontainers.image.title": "devcontainer-feature-myFeature.tgz" } } ], "annotations": { "dev.containers.metadata": "{\"name\": \"My Feature\",\"id\": \"myFeature\",\"version\": \"1.0.0\",\"dependsOn\": {\"ghcr.io/myotherFeature:1\": {\"flag\": true},\"features.azurecr.io/aThirdFeature:1\": {}\",\"features.azurecr.io/aFourthFeature:1.2.3\": {}}}" } } ``` -------------------------------- ### Define Feature Options in devcontainer-feature.json Source: https://containers.dev/implementors/features Example of defining options for a dev container feature. Options are mapped to environment variables and can include type, description, proposals, and default values. ```json { "options": { "optionIdGoesHere": { "type": "string", "description": "Description of the option", "proposals": ["value1", "value2"], "default": "value1" } } } ``` -------------------------------- ### Using Local Environment Variables in devcontainer.json Source: https://containers.dev/implementors/json_reference Shows how to reference environment variables from the host machine within devcontainer.json using the ${localEnv:VARIABLE_NAME} syntax. It includes an example of combining variables and providing default values. ```json "remoteEnv": { "LOCAL_USER_PATH": "${localEnv:HOME}${localEnv:USERPROFILE}" } ``` ```json "remoteEnv": { "VARIABLE_NAME": "${localEnv:VARIABLE_NAME:default_value}" } ``` -------------------------------- ### Using Container Environment Variables in devcontainer.json Source: https://containers.dev/implementors/json_reference Demonstrates how to reference environment variables that are already set within the running container using the ${containerEnv:VARIABLE_NAME} syntax. It includes an example of appending to an existing PATH variable and providing default values. ```json "remoteEnv": { "PATH": "${containerEnv:PATH}:/some/other/path" } ``` ```json "remoteEnv": { "VARIABLE_NAME": "${containerEnv:VARIABLE_NAME:default_value}" } ``` -------------------------------- ### Renaming a Dev Container Feature Example Source: https://containers.dev/implementors/features Illustrates the steps and JSON modifications required to rename a Dev Container Feature, including updating the id, source folder, and optionally other properties like name and documentationURL, while also adding legacyIds. ```json { "id": "docker-from-docker", "version": "2.0.1", "name": "Docker (Docker-from-Docker)", "documentationURL": "https://github.com/devcontainers/features/tree/main/src/docker-from-docker", .... } ``` ```json { "id": "docker-outside-of-docker", "version": "2.0.2", "name": "Docker (Docker-outside-of-Docker)", "documentationURL": "https://github.com/devcontainers/features/tree/main/src/docker-outside-of-docker", "legacyIds": [ "docker-from-docker" ] .... } ``` -------------------------------- ### Example of Resolved Template Options Source: https://containers.dev/implementors/templates This JSON object represents the resolved values for template options after a user has made their selections. It demonstrates how the selected values for `imageVariant`, `nodeVersion`, and `installMaven` are provided to configure the dev container. ```json { "imageVariant":"17-bullseye", "nodeVersion": "latest", "installMaven": "false" } ``` -------------------------------- ### Push Dev Container Templates to OCI Registry using oras Source: https://containers.dev/implementors/templates-distribution This snippet demonstrates how to push Dev Container templates to an OCI registry using the `oras` tool. It iterates through different version tags and pushes the template artifact with custom media types. Ensure `oras` is installed and the registry is accessible. ```shell # ghcr.io/devcontainers/templates/go:1 REGISTRY=ghcr.io NAMESPACE=devcontainers/templates TEMPLATE=go ARTIFACT_PATH=devcontainer-template-go.tgz for VERSION in 1 1.2 1.2.3 latest do oras push ${REGISTRY}/${NAMESPACE}/${TEMPLATE}:${VERSION} \ --config /dev/null:application/vnd.devcontainers \ ./${ARTIFACT_PATH}:application/vnd.devcontainers.layer.v1+tar done ``` -------------------------------- ### Option Name Sanitization for Environment Variables Source: https://containers.dev/implementors/features This JavaScript code snippet sanitizes feature option names to be valid environment variable names. It replaces invalid characters with underscores and ensures the name does not start with a digit or underscore, converting it to uppercase. This is crucial for passing options correctly to feature install scripts. ```javascript function sanitizeOptionName(str) { return str .replace(/[^\w_]/g, '_') .replace(/^[\d_]+/g, '_') .toUpperCase(); } ``` -------------------------------- ### Pre-build and Push Container Image using CLI Source: https://containers.dev/implementors/reference This snippet illustrates how to pre-build a container image with necessary tools and push it to a registry using the Dev Containers CLI. This optimizes container startup times and simplifies configuration management. ```bash devcontainer build --workspace-folder . --push true --image-name : ``` -------------------------------- ### Run Initialization Command (JSON) Source: https://containers.dev/implementors/json_schema Specifies a command to run on the host machine during initialization. This command executes before 'onCreateCommand' and can be a string (run in shell) or an array of strings (run as a single command). ```json { "initializeCommand": "echo 'Initializing container...'" } ``` ```json { "initializeCommand": [ "./scripts/setup.sh", "--option" ] } ``` -------------------------------- ### Configure Dockerfile Build Options Source: https://containers.dev/implementors/json_reference Provides an array of options to be passed directly to the Docker build command. This allows for advanced build configurations, such as adding host entries. ```json { "build": { "options": [ "--add-host=host.docker.internal:host-gateway" ] } } ``` -------------------------------- ### Dev Container CLI Help and Commands Source: https://containers.dev/implementors/reference Displays the help text and available commands for the Dev Container CLI. This output shows the various subcommands like 'up', 'build', 'run-user-commands', etc., along with their options. ```bash devcontainer Commands: devcontainer up Create and run dev container devcontainer build [path] Build a dev container image devcontainer run-user-commands Run user commands devcontainer read-configuration Read configuration devcontainer features Features commands devcontainer templates Templates commands devcontainer exec [args..] Execute a command on a running dev container Options: --help Show help [boolean] --version Show version number [boolean] ``` -------------------------------- ### Define Git LFS Feature in devcontainer-feature.json Source: https://containers.dev/implementors/features Configuration for the Git LFS feature, specifying its ID, version, name, and a post-create command that executes a previously installed script. ```json { "id": "git-lfs", "version": "1.1.0", "name": "Git Large File Support (LFS)", // <...truncated...> "postCreateCommand": "/usr/local/share/pull-git-lfs-artifacts.sh", "installsAfter": [ "ghcr.io/devcontainers/features/common-utils" ] } ``` -------------------------------- ### Publish Dev Container Templates using Dev Container CLI Source: https://containers.dev/implementors/templates-distribution This command publishes Dev Container templates from a local directory to a specified OCI registry. It requires a GitHub token for authentication and specifies the registry and namespace. The `./src` directory is assumed to contain the template structure. ```shell [/tmp]$ GITHUB_TOKEN="$CR_PAT" devcontainer templates publish -r ghcr.io -n devcontainers/templates ./src ``` -------------------------------- ### Dev Container Lifecycle Script String vs. Array Syntax Source: https://containers.dev/implementors/json_reference Illustrates the difference between string and array syntax for dev container lifecycle commands. String syntax executes commands via a shell (e.g., /bin/sh), allowing for command chaining with '&&'. Array syntax executes commands directly without a shell. ```json { "onCreateCommand": "apt-get update && apt-get install -y curl", "postCreateCommand": [ "npm", "install" ] } ``` -------------------------------- ### Configuring Port Attributes in Dev Container Source: https://containers.dev/implementors/json_reference The `portsAttributes` property allows detailed configuration for specific ports, including setting labels. It maps port identifiers to their attributes. An example shows how to label port 3000. ```json { "name": "My Dev Container", "portsAttributes": { "3000": {"label": "Application port"} } } ``` -------------------------------- ### Apply a Published Dev Container Template using CLI Source: https://containers.dev/implementors/templates-distribution This command demonstrates how to apply a previously published Dev Container template using the Dev Container CLI. It specifies the template's OCI path and accepts template arguments as a JSON string. ```shell [/tmp]$ devcontainer templates apply \ -t 'ghcr.io/devcontainers/templates/color' \ -a '{"favorite": "red"}' ``` -------------------------------- ### Setting Default Port Attributes in Dev Container Source: https://containers.dev/implementors/json_reference The `otherPortsAttributes` property defines default options for ports, ranges, and hosts not explicitly configured in `portsAttributes`. It can control behaviors like `onAutoForward`. An example sets auto-forwarding to silent. ```json { "name": "My Dev Container", "otherPortsAttributes": { "onAutoForward": "silent" } } ``` -------------------------------- ### Specify Minimum Host Requirements in Dev Container Config Source: https://containers.dev/implementors/json_reference Define the minimum hardware resources required for the development container. This includes CPU cores, memory, storage, and GPU specifications. These properties help cloud services select appropriate compute instances and can trigger warnings if the host environment doesn't meet the specified needs. ```json { "hostRequirements": { "cpus": 2, "memory": "4gb", "storage": "32gb", "gpu": true } } ``` ```json { "hostRequirements": { "cpus": 4, "memory": "16gb", "storage": "100gb", "gpu": { "cores": 1000, "memory": "32gb" } } } ``` ```json { "hostRequirements": { "gpu": "optional" } } ``` -------------------------------- ### Configure Docker Compose Files Source: https://containers.dev/implementors/json_reference Specifies the Docker Compose file(s) to be used for setting up the development environment. Supports a single file path or an ordered list for overriding configurations. ```json { "dockerComposeFile": "docker-compose.yml" } ``` ```json { "dockerComposeFile": [ "docker-compose.yml", "docker-compose.override.yml" ] } ``` -------------------------------- ### Define Post-Creation Command (JSON) Source: https://containers.dev/implementors/json_schema Specifies a command to run after the container has been created. This executes after 'updateContentCommand' and before 'postStartCommand'. Supports string or array formats. ```json { "postCreateCommand": "chmod +x ./run.sh" } ``` ```json { "postCreateCommand": [ "python", "./scripts/setup_db.py" ] } ``` -------------------------------- ### Declare Feature Dependencies in devcontainer-feature.json Source: https://containers.dev/implementors/features The `dependsOn` property in `devcontainer-feature.json` specifies required Features that must be installed before the current Feature. Dependencies can include version constraints and options, and are evaluated recursively. If any dependency cannot be satisfied, dev container creation fails. ```json { "name": "My Feature", "id": "myFeature", "version": "1.0.0", "dependsOn": { "foo:1": { "flag": true }, "bar:1.2.3": {}, "baz@sha256:a4cdc44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {} } } ``` -------------------------------- ### Modified .devcontainer.json after Option Resolution Source: https://containers.dev/implementors/templates This is an example of a `.devcontainer.json` file after template options have been resolved and applied. The placeholders like `${templateOption:imageVariant}` have been replaced with the user's selected values, resulting in a customized container configuration. ```json { "name": "Go", "image": "mcr.microsoft.com/devcontainers/go:0-17-bullseye", "features": { "ghcr.io/devcontainers/features/node:1": { "version": "latest", "installMaven": "false" } }, ... } ``` -------------------------------- ### Configure Dockerfile Build Arguments Source: https://containers.dev/implementors/json_reference Specifies build arguments to be passed when building a Dockerfile. Values can reference environment variables. This is useful for customizing the image build process. ```json { "build": { "args": { "MYARG": "MYVALUE", "MYARGFROMENVVAR": "${localEnv:VARIABLE_NAME}" } } } ``` -------------------------------- ### Define Container Creation Command (JSON) Source: https://containers.dev/implementors/json_schema Specifies a command to execute when creating the container. This runs after 'initializeCommand' and before 'updateContentCommand'. Can be a string or an array of strings. ```json { "onCreateCommand": "npm install" } ``` ```json { "onCreateCommand": [ "apt-get update", "apt-get install -y --no-install-recommends some-package" ] } ``` -------------------------------- ### VS Code Customizations in devcontainer.json Source: https://containers.dev/implementors/contributing This snippet demonstrates how to configure tool-specific properties, particularly for VS Code, within the `customizations` object in a `devcontainer.json` file. It shows how to set default settings for VS Code within the container. ```json // Configure tool-specific properties. "customizations": { // Configure properties specific to VS Code. "vscode": { // Set *default* container specific settings.json values on container create. "settings": {}, // Additional VS Code specific properties... } }, ```