

# Custom Images in Amazon SageMaker Studio Classic
<a name="studio-byoi"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

A SageMaker image is a file that identifies the kernels, language packages, and other dependencies required to run a Jupyter notebook in Amazon SageMaker Studio Classic. These images are used to create an environment that you then run Jupyter notebooks from. Amazon SageMaker AI provides many built-in images for you to use. For the list of built-in images, see [Amazon SageMaker Images Available for Use With Studio Classic Notebooks](notebooks-available-images.md).

If you need different functionality, you can bring your own custom images to Studio Classic. You can create images and image versions, and attach image versions to your domain or shared space, using the SageMaker AI control panel, the [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html), and the [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/). You can also create images and image versions using the SageMaker AI console, even if you haven't onboarded to a SageMaker AI domain. SageMaker AI provides sample Dockerfiles to use as a starting point for your custom SageMaker images in the [SageMaker Studio Classic Custom Image Samples](https://github.com/aws-samples/sagemaker-studio-custom-image-samples/) repository.

The following topics explain how to bring your own image using the SageMaker AI console or AWS CLI, then launch the image in Studio Classic. For a similar blog article, see [Bringing your own R environment to Amazon SageMaker Studio Classic](https://aws.amazon.com/blogs/machine-learning/bringing-your-own-r-environment-to-amazon-sagemaker-studio/). For notebooks that show how to bring your own image for use in training and inference, see [Amazon SageMaker Studio Classic Container Build CLI](https://github.com/aws/amazon-sagemaker-examples/tree/main/aws_sagemaker_studio/sagemaker_studio_image_build).

## Key terminology
<a name="studio-byoi-basics"></a>

The following section defines key terms for bringing your own image to use with Studio Classic.
+ **Dockerfile:** A Dockerfile is a file that identifies the language packages and other dependencies for your Docker image.
+ **Docker image:** The Docker image is a built Dockerfile. This image is checked into Amazon ECR and serves as the basis of the SageMaker AI image.
+ **SageMaker image:** A SageMaker image is a holder for a set of SageMaker AI image versions based on Docker images. Each image version is immutable.
+ **Image version:** An image version of a SageMaker image represents a Docker image and is stored in an Amazon ECR repository. Each image version is immutable. These image versions can be attached to a domain or shared space and used with Studio Classic.

**Topics**
+ [Key terminology](#studio-byoi-basics)
+ [Custom SageMaker Image Specifications for Amazon SageMaker Studio Classic](studio-byoi-specs.md)
+ [Prerequisites for Custom Images in Amazon SageMaker Studio Classic](studio-byoi-prereq.md)
+ [Add a Docker Image Compatible with Amazon SageMaker Studio Classic to Amazon ECR](studio-byoi-sdk-add-container-image.md)
+ [Create a Custom SageMaker Image for Amazon SageMaker Studio Classic](studio-byoi-create.md)
+ [Attach a Custom SageMaker Image in Amazon SageMaker Studio Classic](studio-byoi-attach.md)
+ [Launch a Custom SageMaker Image in Amazon SageMaker Studio Classic](studio-byoi-launch.md)
+ [Clean Up Resources for Custom Images in Amazon SageMaker Studio Classic](studio-byoi-cleanup.md)

# Custom SageMaker Image Specifications for Amazon SageMaker Studio Classic
<a name="studio-byoi-specs"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

The following specifications apply to the container image that is represented by a SageMaker AI image version.

**Running the image**  
`ENTRYPOINT` and `CMD` instructions are overridden to enable the image to run as a KernelGateway app.  
Port 8888 in the image is reserved for running the KernelGateway web server.

**Stopping the image**  
The `DeleteApp` API issues the equivalent of a `docker stop` command. Other processes in the container won’t get the SIGKILL/SIGTERM signals.

**Kernel discovery**  
SageMaker AI recognizes kernels as defined by Jupyter [kernel specs](https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs).  
You can specify a list of kernels to display before running the image. If not specified, python3 is displayed. Use the [DescribeAppImageConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAppImageConfig.html) API to view the list of kernels.  
Conda environments are recognized as kernel specs by default. 

**File system**  
The `/opt/.sagemakerinternal` and `/opt/ml` directories are reserved. Any data in these directories might not be visible at runtime.

**User data**  
Each user in a domain gets a user directory on a shared Amazon Elastic File System volume in the image. The location of the current user's directory on the Amazon EFS volume is configurable. By default, the location of the directory is `/home/sagemaker-user`.  
SageMaker AI configures POSIX UID/GID mappings between the image and the host. This defaults to mapping the root user's UID/GID (0/0) to the UID/GID on the host.  
You can specify these values using the [CreateAppImageConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateAppImageConfig.html) API.

**GID/UID limits**  
Amazon SageMaker Studio Classic only supports the following `DefaultUID` and `DefaultGID` combinations:   
+  DefaultUID: 1000 and DefaultGID: 100, which corresponds to a non-priveleged user.
+  DefaultUID: 0 and DefaultGID: 0, which corresponds to root access.

**Metadata**  
A metadata file is located at `/opt/ml/metadata/resource-metadata.json`. No additional environment variables are added to the variables defined in the image. For more information, see [Get App Metadata](notebooks-run-and-manage-metadata.md#notebooks-run-and-manage-metadata-app).

**GPU**  
On a GPU instance, the image is run with the `--gpus` option. Only the CUDA toolkit should be included in the image not the NVIDIA drivers. For more information, see [NVIDIA User Guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/user-guide.html).

**Metrics and logging**  
Logs from the KernelGateway process are sent to Amazon CloudWatch in the customer’s account. The name of the log group is `/aws/sagemaker/studio`. The name of the log stream is `$domainID/$userProfileName/KernelGateway/$appName`.

**Image size**  
Limited to 35 GB. To view the size of your image, run `docker image ls`.  


## Sample Dockerfile
<a name="studio-byoi-specs-sample"></a>

The following sample Dockerfile creates an image based Amazon Linux 2, installs third party packages and the `python3` kernel, and sets the scope to the non-privileged user.

```
FROM public.ecr.aws/amazonlinux/amazonlinux:2

ARG NB_USER="sagemaker-user"
ARG NB_UID="1000"
ARG NB_GID="100"

RUN \
    yum install --assumeyes python3 shadow-utils && \
    useradd --create-home --shell /bin/bash --gid "${NB_GID}" --uid ${NB_UID} ${NB_USER} && \
    yum clean all && \
    jupyter-activity-monitor-extension \
    python3 -m pip install ipykernel && \
    python3 -m ipykernel install

USER ${NB_UID}
```

# Prerequisites for Custom Images in Amazon SageMaker Studio Classic
<a name="studio-byoi-prereq"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

You must satisfy the following prerequisites to bring your own container for use with Amazon SageMaker Studio Classic.
+ The Docker application. For information about setting up Docker, see [Orientation and setup](https://docs.docker.com/get-started/).
+ Install the AWS CLI by following the steps in [Getting started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).
+ A local copy of any Dockerfile for creating a Studio Classic compatible image. For sample custom images, see the [SageMaker AI Studio Classic custom image samples](https://github.com/aws-samples/sagemaker-studio-custom-image-samples/) repository.
+ Permissions to access the Amazon Elastic Container Registry (Amazon ECR) service. For more information, see [Amazon ECR Managed Policies](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ecr_managed_policies.html).
+ An AWS Identity and Access Management execution role that has the [AmazonSageMakerFullAccess](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/AmazonSageMakerFullAccess) policy attached. If you have onboarded to Amazon SageMaker AI domain, you can get the role from the **Domain Summary** section of the SageMaker AI control panel.
+ Install the Studio Classic image build CLI by following the steps in [SageMaker Docker Build](https://github.com/aws-samples/sagemaker-studio-image-build-cli). This CLI enables you to build a Dockerfile using AWS CodeBuild.

# Add a Docker Image Compatible with Amazon SageMaker Studio Classic to Amazon ECR
<a name="studio-byoi-sdk-add-container-image"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

You perform the following steps to add a container image to Amazon ECR:
+ Create an Amazon ECR repository.
+ Authenticate to Amazon ECR.
+ Build a Docker image compatible with Studio Classic.
+ Push the image to the Amazon ECR repository.

**Note**  
The Amazon ECR repository must be in the same AWS Region as Studio Classic.

**To build and add a container image to Amazon ECR**

1. Create an Amazon ECR repository using the AWS CLI. To create the repository using the Amazon ECR console, see [Creating a repository](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html).

   ```
   aws ecr create-repository \
       --repository-name smstudio-custom \
       --image-scanning-configuration scanOnPush=true
   ```

   The response should look similar to the following.

   ```
   {
       "repository": {
           "repositoryArn": "arn:aws:ecr:us-east-2:acct-id:repository/smstudio-custom",
           "registryId": "acct-id",
           "repositoryName": "smstudio-custom",
           "repositoryUri": "acct-id.dkr.ecr.us-east-2.amazonaws.com/smstudio-custom",
           ...
       }
   }
   ```

1. Build the `Dockerfile` using the Studio Classic image build CLI. The period (.) specifies that the Dockerfile should be in the context of the build command. This command builds the image and uploads the built image to the ECR repo. It then outputs the image URI.

   ```
   sm-docker build . --repository smstudio-custom:custom
   ```

   The response should look similar to the following.

   ```
   Image URI: <acct-id>.dkr.ecr.<region>.amazonaws.com/<image_name>
   ```

# Create a Custom SageMaker Image for Amazon SageMaker Studio Classic
<a name="studio-byoi-create"></a>

**Important**  
Custom IAM policies that allow Amazon SageMaker Studio or Amazon SageMaker Studio Classic to create Amazon SageMaker resources must also grant permissions to add tags to those resources. The permission to add tags to resources is required because Studio and Studio Classic automatically tag any resources they create. If an IAM policy allows Studio and Studio Classic to create resources but does not allow tagging, "AccessDenied" errors can occur when trying to create resources. For more information, see [Provide permissions for tagging SageMaker AI resources](security_iam_id-based-policy-examples.md#grant-tagging-permissions).  
[AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md) that give permissions to create SageMaker resources already include permissions to add tags while creating those resources.

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

This topic describes how you can create a custom SageMaker image using the SageMaker AI console or AWS CLI.

When you create an image from the console, SageMaker AI also creates an initial image version. The image version represents a container image in [Amazon Elastic Container Registry (ECR)](https://console.aws.amazon.com/ecr/). The container image must satisfy the requirements to be used in Amazon SageMaker Studio Classic. For more information, see [Custom SageMaker Image Specifications for Amazon SageMaker Studio Classic](studio-byoi-specs.md). For information on testing your image locally and resolving common issues, see the [SageMaker Studio Classic Custom Image Samples repo](https://github.com/aws-samples/sagemaker-studio-custom-image-samples/blob/main/DEVELOPMENT.md).

After you have created your custom SageMaker image, you must attach it to your domain or shared space to use it with Studio Classic. For more information, see [Attach a Custom SageMaker Image in Amazon SageMaker Studio Classic](studio-byoi-attach.md).

## Create a SageMaker image from the console
<a name="studio-byoi-create-console"></a>

The following section demonstrates how to create a custom SageMaker image from the SageMaker AI console.

**To create an image**

1. Open the Amazon SageMaker AI console at [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/).

1. On the left navigation pane, choose **Admin configurations**.

1. Under **Admin configurations**, choose **Images**. 

1. On the **Custom images** page, choose **Create image**.

1. For **Image source**, enter the registry path to the container image in Amazon ECR. The path is in the following format:

   ` acct-id.dkr.ecr.region.amazonaws.com/repo-name[:tag] or [@digest] `

1. Choose **Next**.

1. Under **Image properties**, enter the following:
   + Image name – The name must be unique to your account in the current AWS Region.
   + (Optional) Display name – The name displayed in the Studio Classic user interface. When not provided, `Image name` is displayed.
   + (Optional) Description – A description of the image.
   + IAM role – The role must have the [AmazonSageMakerFullAccess](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/AmazonSageMakerFullAccess) policy attached. Use the dropdown menu to choose one of the following options:
     + Create a new role – Specify any additional Amazon Simple Storage Service (Amazon S3) buckets that you want users of your notebooks to have access to. If you don't want to allow access to additional buckets, choose **None**.

       SageMaker AI attaches the `AmazonSageMakerFullAccess` policy to the role. The role allows users of your notebooks access to the S3 buckets listed next to the checkmarks.
     + Enter a custom IAM role ARN – Enter the Amazon Resource Name (ARN) of your IAM role.
     + Use existing role – Choose one of your existing roles from the list.
   + (Optional) Image tags – Choose **Add new tag**. You can add up to 50 tags. Tags are searchable using the Studio Classic user interface, the SageMaker AI console, or the SageMaker AI `Search` API.

1. Choose **Submit**.

The new image is displayed in the **Custom images** list and briefly highlighted. After the image has been successfully created, you can choose the image name to view its properties or choose **Create version** to create another version.

**To create another image version**

1. Choose **Create version** on the same row as the image.

1. For **Image source**, enter the registry path to the Amazon ECR container image. The container image shouldn't be the same image as used in a previous version of the SageMaker image.

## Create a SageMaker image from the AWS CLI
<a name="studio-byoi-sdk-create-image"></a>

You perform the following steps to create a SageMaker image from the container image using the AWS CLI.
+ Create an `Image`.
+ Create an `ImageVersion`.
+ Create a configuration file.
+ Create an `AppImageConfig`.

**To create the SageMaker image entities**

1. Create a SageMaker image.

   ```
   aws sagemaker create-image \
       --image-name custom-image \
       --role-arn arn:aws:iam::<acct-id>:role/service-role/<execution-role>
   ```

   The response should look similar to the following.

   ```
   {
       "ImageArn": "arn:aws:sagemaker:us-east-2:acct-id:image/custom-image"
   }
   ```

1. Create a SageMaker image version from the container image.

   ```
   aws sagemaker create-image-version \
       --image-name custom-image \
       --base-image <acct-id>.dkr.ecr.<region>.amazonaws.com/smstudio-custom:custom-image
   ```

   The response should look similar to the following.

   ```
   {
       "ImageVersionArn": "arn:aws:sagemaker:us-east-2:acct-id:image-version/custom-image/1"
   }
   ```

1. Check that the image version was successfully created.

   ```
   aws sagemaker describe-image-version \
       --image-name custom-image \
       --version-number 1
   ```

   The response should look similar to the following.

   ```
   {
       "ImageVersionArn": "arn:aws:sagemaker:us-east-2:acct-id:image-version/custom-image/1",
       "ImageVersionStatus": "CREATED"
   }
   ```
**Note**  
If the response is `"ImageVersionStatus": "CREATED_FAILED"`, the response also includes the failure reason. A permissions issue is a common cause of failure. You also can check your Amazon CloudWatch logs if you experience a failure when starting or running the KernelGateway app for a custom image. The name of the log group is `/aws/sagemaker/studio`. The name of the log stream is `$domainID/$userProfileName/KernelGateway/$appName`.

1. Create a configuration file, named `app-image-config-input.json`. The `Name` value of `KernelSpecs` must match the name of the kernelSpec available in the Image associated with this `AppImageConfig`. This value is case sensitive. You can find the available kernelSpecs in an image by running `jupyter-kernelspec list` from a shell inside the container. `MountPath` is the path within the image to mount your Amazon Elastic File System (Amazon EFS) home directory. It needs to be different from the path you use inside the container because that path will be overridden when your Amazon EFS home directory is mounted.
**Note**  
The following `DefaultUID` and `DefaultGID` combinations are the only accepted values:   
 DefaultUID: 1000 and DefaultGID: 100 
 DefaultUID: 0 and DefaultGID: 0 

   ```
   {
       "AppImageConfigName": "custom-image-config",
       "KernelGatewayImageConfig": {
           "KernelSpecs": [
               {
                   "Name": "python3",
                   "DisplayName": "Python 3 (ipykernel)"
               }
           ],
           "FileSystemConfig": {
               "MountPath": "/home/sagemaker-user",
               "DefaultUid": 1000,
               "DefaultGid": 100
           }
       }
   }
   ```

1. Create the AppImageConfig using the file created in the previous step.

   ```
   aws sagemaker create-app-image-config \
       --cli-input-json file://app-image-config-input.json
   ```

   The response should look similar to the following.

   ```
   {
       "AppImageConfigArn": "arn:aws:sagemaker:us-east-2:acct-id:app-image-config/custom-image-config"
   }
   ```

# Attach a Custom SageMaker Image in Amazon SageMaker Studio Classic
<a name="studio-byoi-attach"></a>

**Important**  
Custom IAM policies that allow Amazon SageMaker Studio or Amazon SageMaker Studio Classic to create Amazon SageMaker resources must also grant permissions to add tags to those resources. The permission to add tags to resources is required because Studio and Studio Classic automatically tag any resources they create. If an IAM policy allows Studio and Studio Classic to create resources but does not allow tagging, "AccessDenied" errors can occur when trying to create resources. For more information, see [Provide permissions for tagging SageMaker AI resources](security_iam_id-based-policy-examples.md#grant-tagging-permissions).  
[AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md) that give permissions to create SageMaker resources already include permissions to add tags while creating those resources.

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

To use a custom SageMaker image, you must attach a version of the image to your domain or shared space. When you attach an image version, it appears in the SageMaker Studio Classic Launcher and is available in the **Select image** dropdown list, which users use to launch an activity or change the image used by a notebook.

To make a custom SageMaker image available to all users within a domain, you attach the image to the domain. To make an image available to all users within a shared space, you can attach the image to the shared space. To make an image available to a single user, you attach the image to the user's profile. When you attach an image, SageMaker AI uses the latest image version by default. You can also attach a specific image version. After you attach the version, you can choose the version from the SageMaker AI Launcher or the image selector when you launch a notebook.

There is a limit to the number of image versions that can be attached at any given time. After you reach the limit, you must detach a version in order to attach another version of the image.

The following sections demonstrate how to attach a custom SageMaker image to your domain using either the SageMaker AI console or the AWS CLI. You can only attach a custom image to a share space using the AWS CLI.

## Attach the SageMaker image to a domain
<a name="studio-byoi-attach-domain"></a>

### Attach the SageMaker image using the Console
<a name="studio-byoi-attach-existing"></a>

This topic describes how you can attach an existing custom SageMaker image version to your domain using the SageMaker AI control panel. You can also create a custom SageMaker image and image version, and then attach that version to your domain. For the procedure to create an image and image version, see [Create a Custom SageMaker Image for Amazon SageMaker Studio Classic](studio-byoi-create.md).

**To attach an existing image**

1. Open the Amazon SageMaker AI console at [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/).

1. On the left navigation pane, choose **Admin configurations**.

1. Under **Admin configurations**, choose **domains**. 

1. From the **Domains** page, select the domain to attach the image to.

1. From the **Domain details** page, select the **Environment** tab.

1. On the **Environment** tab, under **Custom SageMaker Studio Classic images attached to domain**, choose **Attach image**.

1. For **Image source**, choose **Existing image**.

1. Choose an existing image from the list.

1. Choose a version of the image from the list.

1. Choose **Next**.

1. Verify the values for **Image name**, **Image display name**, and **Description**.

1. Choose the IAM role. For more information, see [Create a Custom SageMaker Image for Amazon SageMaker Studio Classic](studio-byoi-create.md).

1. (Optional) Add tags for the image.

1. Specify the EFS mount path. This is the path within the image to mount the user's Amazon Elastic File System (EFS) home directory.

1. For **Image type**, select **SageMaker Studio image**

1. For **Kernel name**, enter the name of an existing kernel in the image. For information on how to get the kernel information from the image, see [DEVELOPMENT](https://github.com/aws-samples/sagemaker-studio-custom-image-samples/blob/main/DEVELOPMENT.md) in the SageMaker Studio Classic Custom Image Samples repository. For more information, see the **Kernel discovery** and **User data** sections of [Custom SageMaker Image Specifications for Amazon SageMaker Studio Classic](studio-byoi-specs.md).

1. (Optional) For **Kernel display name**, enter the display name for the kernel.

1. Choose **Add kernel**.

1. Choose **Submit**. 

   1. Wait for the image version to be attached to the domain. When attached, the version is displayed in the **Custom images** list and briefly highlighted.

### Attach the SageMaker image using the AWS CLI
<a name="studio-byoi-sdk-attach"></a>

The following sections demonstrate how to attach a custom SageMaker image when creating a new domain or updating your existing domain using the AWS CLI.

#### Attach the SageMaker image to a new domain
<a name="studio-byoi-sdk-attach-new-domain"></a>

The following section demonstrates how to create a new domain with the version attached. These steps require that you specify the Amazon Virtual Private Cloud (VPC) information and execution role required to create the domain. You perform the following steps to create the domain and attach the custom SageMaker image:
+ Get your default VPC ID and subnet IDs.
+ Create the configuration file for the domain, which specifies the image.
+ Create the domain with the configuration file.

**To add the custom SageMaker image to your domain**

1. Get your default VPC ID.

   ```
   aws ec2 describe-vpcs \
       --filters Name=isDefault,Values=true \
       --query "Vpcs[0].VpcId" --output text
   ```

   The response should look similar to the following.

   ```
   vpc-xxxxxxxx
   ```

1. Get your default subnet IDs using the VPC ID from the previous step.

   ```
   aws ec2 describe-subnets \
       --filters Name=vpc-id,Values=<vpc-id> \
       --query "Subnets[*].SubnetId" --output json
   ```

   The response should look similar to the following.

   ```
   [
       "subnet-b55171dd",
       "subnet-8a5f99c6",
       "subnet-e88d1392"
   ]
   ```

1. Create a configuration file named `create-domain-input.json`. Insert the VPC ID, subnet IDs, `ImageName`, and `AppImageConfigName` from the previous steps. Because `ImageVersionNumber` isn't specified, the latest version of the image is used, which is the only version in this case.

   ```
   {
       "DomainName": "domain-with-custom-image",
       "VpcId": "<vpc-id>",
       "SubnetIds": [
           "<subnet-ids>"
       ],
       "DefaultUserSettings": {
           "ExecutionRole": "<execution-role>",
           "KernelGatewayAppSettings": {
               "CustomImages": [
                   {
                       "ImageName": "custom-image",
                       "AppImageConfigName": "custom-image-config"
                   }
               ]
           }
       },
       "AuthMode": "IAM"
   }
   ```

1. Create the domain with the attached custom SageMaker image.

   ```
   aws sagemaker create-domain \
       --cli-input-json file://create-domain-input.json
   ```

   The response should look similar to the following.

   ```
   {
       "DomainArn": "arn:aws:sagemaker:us-east-2:acct-id:domain/d-xxxxxxxxxxxx",
       "Url": "https://d-xxxxxxxxxxxx.studio.us-east-2.sagemaker.aws/..."
   }
   ```

#### Attach the SageMaker image to your current domain
<a name="studio-byoi-sdk-attach-current-domain"></a>

If you have onboarded to a SageMaker AI domain, you can attach the custom image to your current domain. For more information about onboarding to a SageMaker AI domain, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md). You don't need to specify the VPC information and execution role when attaching a custom image to your current domain. After you attach the version, you must delete all the apps in your domain and reopen Studio Classic. For information about deleting the apps, see [Delete an Amazon SageMaker AI domain](gs-studio-delete-domain.md).

You perform the following steps to add the SageMaker image to your current domain.
+ Get your `DomainID` from SageMaker AI control panel.
+ Use the `DomainID` to get the `DefaultUserSettings` for the domain.
+ Add the `ImageName` and `AppImageConfig` as a `CustomImage` to the `DefaultUserSettings`.
+ Update your domain to include the custom image.

**To add the custom SageMaker image to your domain**

1. Open the Amazon SageMaker AI console at [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/).

1. On the left navigation pane, choose **Admin configurations**.

1. Under **Admin configurations**, choose **domains**. 

1. From the **Domains** page, select the domain to attach the image to.

1. From the **Domain details** page, select the **Domain settings** tab.

1. From the **Domain settings** tab, under **General settings**, find the `DomainId`. The ID is in the following format: `d-xxxxxxxxxxxx`.

1. Use the domain ID to get the description of the domain.

   ```
   aws sagemaker describe-domain \
       --domain-id <d-xxxxxxxxxxxx>
   ```

   The response should look similar to the following.

   ```
   {
       "DomainId": "d-xxxxxxxxxxxx",
       "DefaultUserSettings": {
         "KernelGatewayAppSettings": {
           "CustomImages": [
           ],
           ...
         }
       }
   }
   ```

1. Save the default user settings section of the response to a file named `default-user-settings.json`.

1. Insert the `ImageName` and `AppImageConfigName` from the previous steps as a custom image. Because `ImageVersionNumber` isn't specified, the latest version of the image is used, which is the only version in this case.

   ```
   {
       "DefaultUserSettings": {
           "KernelGatewayAppSettings": { 
              "CustomImages": [ 
                 { 
                    "ImageName": "string",
                    "AppImageConfigName": "string"
                 }
              ],
              ...
           }
       }
   }
   ```

1. Use the domain ID and default user settings file to update your domain.

   ```
   aws sagemaker update-domain \
       --domain-id <d-xxxxxxxxxxxx> \
       --cli-input-json file://default-user-settings.json
   ```

   The response should look similar to the following.

   ```
   {
       "DomainArn": "arn:aws:sagemaker:us-east-2:acct-id:domain/d-xxxxxxxxxxxx"
   }
   ```

## Attach the SageMaker image to a shared space
<a name="studio-byoi-attach-shared-space"></a>

You can only attach the SageMaker image to a shared space using the AWS CLI. After you attach the version, you must delete all of the applications in your shared space and reopen Studio Classic. For information about deleting the apps, see [Delete an Amazon SageMaker AI domain](gs-studio-delete-domain.md).

You perform the following steps to add the SageMaker image to a shared space.
+ Get your `DomainID` from SageMaker AI control panel.
+ Use the `DomainID` to get the `DefaultSpaceSettings` for the domain.
+ Add the `ImageName` and `AppImageConfig` as a `CustomImage` to the `DefaultSpaceSettings`.
+ Update your domain to include the custom image for the shared space.

**To add the custom SageMaker image to your shared space**

1. Open the Amazon SageMaker AI console at [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/).

1. On the left navigation pane, choose **Admin configurations**.

1. Under **Admin configurations**, choose **domains**. 

1. From the **Domains** page, select the domain to attach the image to.

1. From the **Domain details** page, select the **Domain settings** tab.

1. From the **Domain settings** tab, under **General settings**, find the `DomainId`. The ID is in the following format: `d-xxxxxxxxxxxx`.

1. Use the domain ID to get the description of the domain.

   ```
   aws sagemaker describe-domain \
       --domain-id <d-xxxxxxxxxxxx>
   ```

   The response should look similar to the following.

   ```
   {
       "DomainId": "d-xxxxxxxxxxxx",
       ...
       "DefaultSpaceSettings": {
         "KernelGatewayAppSettings": {
           "CustomImages": [
           ],
           ...
         }
       }
   }
   ```

1. Save the default space settings section of the response to a file named `default-space-settings.json`.

1. Insert the `ImageName` and `AppImageConfigName` from the previous steps as a custom image. Because `ImageVersionNumber` isn't specified, the latest version of the image is used, which is the only version in this case.

   ```
   {
       "DefaultSpaceSettings": {
           "KernelGatewayAppSettings": { 
              "CustomImages": [ 
                 { 
                    "ImageName": "string",
                    "AppImageConfigName": "string"
                 }
              ],
              ...
           }
       }
   }
   ```

1. Use the domain ID and default space settings file to update your domain.

   ```
   aws sagemaker update-domain \
       --domain-id <d-xxxxxxxxxxxx> \
       --cli-input-json file://default-space-settings.json
   ```

   The response should look similar to the following.

   ```
   {
       "DomainArn": "arn:aws:sagemaker:us-east-2:acct-id:domain/d-xxxxxxxxxxxx"
   }
   ```

## View the attached image in SageMaker AI
<a name="studio-byoi-sdk-view"></a>

After you create the custom SageMaker image and attach it to your domain, the image appears in the **Environment** tab of the domain. You can only view the attached images for shared spaces using the AWS CLI by using the following command.

```
aws sagemaker describe-domain \
    --domain-id <d-xxxxxxxxxxxx>
```

# Launch a Custom SageMaker Image in Amazon SageMaker Studio Classic
<a name="studio-byoi-launch"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

After you create your custom SageMaker image and attach it to your domain or shared space, the custom image and kernel appear in selectors in the **Change environment** dialog box of the Studio Classic Launcher.

**To launch and select your custom image and kernel**

1. In Amazon SageMaker Studio Classic, open the Launcher. To open the Launcher, choose **Amazon SageMaker Studio Classic** at the top left of the Studio Classic interface or use the keyboard shortcut `Ctrl + Shift + L`.

   To learn about all the available ways to open the Launcher, see [Use the Amazon SageMaker Studio Classic Launcher](studio-launcher.md)  
![\[SageMaker Studio Classic launcher.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/studio-new-launcher.png)

1. In the Launcher, in the **Notebooks and compute resources** section, choose **Change environment**.

1. In the **Change environment** dialog, use the dropdown menus to select your **Image** from the **Custom Image** section, and your **Kernel**, then choose **Select**.

1. In the Launcher, choose **Create notebook** or **Open image terminal**. Your notebook or terminal launches in the selected custom image and kernel.

To change your image or kernel in an open notebook, see [Change the Image or a Kernel for an Amazon SageMaker Studio Classic Notebook](notebooks-run-and-manage-change-image.md).

**Note**  
If you encounter an error when launching the image, check your Amazon CloudWatch logs. The name of the log group is `/aws/sagemaker/studio`. The name of the log stream is `$domainID/$userProfileName/KernelGateway/$appName`.

# Clean Up Resources for Custom Images in Amazon SageMaker Studio Classic
<a name="studio-byoi-cleanup"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the Studio Classic application. For information about using the updated Studio experience, see [Amazon SageMaker Studio](studio-updated.md).  
Studio Classic is still maintained for existing workloads but is no longer available for onboarding. You can only stop or delete existing Studio Classic applications and cannot create new ones. We recommend that you [migrate your workload to the new Studio experience](studio-updated-migrate.md).

The following sections show how to clean up the resources you created in the previous sections from the SageMaker AI console or AWS CLI. You perform the following steps to clean up the resources:
+ Detach the image and image versions from your domain.
+ Delete the image, image version, and app image config.
+ Delete the container image and repository from Amazon ECR. For more information, see [Deleting a repository](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-delete.html).

## Clean up resources from the SageMaker AI console
<a name="studio-byoi-detach"></a>

The following section shows how to clean up resources from the SageMaker AI console.

When you detach an image from a domain, all versions of the image are detached. When an image is detached, all users of the domain lose access to the image versions. A running notebook that has a kernel session on an image version when the version is detached, continues to run. When the notebook is stopped or the kernel is shut down, the image version becomes unavailable.

**To detach an image**

1. Open the Amazon SageMaker AI console at [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/).

1. On the left navigation pane, choose **Admin configurations**.

1. Under **Admin configurations**, choose **Images**. 

1. Under **Custom SageMaker Studio Classic images attached to domain**, choose the image and then choose **Detach**.

1. (Optional) To delete the image and all versions from SageMaker AI, select **Also delete the selected images ...**. This does not delete the associated container images from Amazon ECR.

1. Choose **Detach**.

## Clean up resources from the AWS CLI
<a name="studio-byoi-sdk-cleanup"></a>

The following section shows how to clean up resources from the AWS CLI.

**To clean up resources**

1. Detach the image and image versions from your domain by passing an empty custom image list to the domain. Open the `default-user-settings.json` file you created in [Attach the SageMaker image to your current domain](studio-byoi-attach.md#studio-byoi-sdk-attach-current-domain). To detach the image and image version from a shared space, open the `default-space-settings.json` file.

1. Delete the custom images and then save the file.

   ```
   "DefaultUserSettings": {
     "KernelGatewayAppSettings": {
        "CustomImages": [
        ],
        ...
     },
     ...
   }
   ```

1. Use the domain ID and default user settings file to update your domain. To update your shared space, use the default space settings file.

   ```
   aws sagemaker update-domain \
       --domain-id <d-xxxxxxxxxxxx> \
       --cli-input-json file://default-user-settings.json
   ```

   The response should look similar to the following.

   ```
   {
       "DomainArn": "arn:aws:sagemaker:us-east-2:acct-id:domain/d-xxxxxxxxxxxx"
   }
   ```

1. Delete the app image config.

   ```
   aws sagemaker delete-app-image-config \
       --app-image-config-name custom-image-config
   ```

1. Delete the SageMaker image, which also deletes all image versions. The container images in ECR that are represented by the image versions are not deleted.

   ```
   aws sagemaker delete-image \
       --image-name custom-image
   ```