All Products
Search
Document Center

Function Compute:Build Custom Image Templates

Last Updated:Jul 15, 2026

Built-in sandbox templates provide a baseline runtime environment. When you need to preinstall application dependencies, configure a specific toolchain, or pin the runtime environment, build a custom template. After the template build finishes, you can use that template directly when creating sandboxes and avoid reinstalling dependencies every time.

Quick Start

Prepare ACR EE

  1. Create an ACR EE instance under the same UID and in the same region as FC Agent Sandbox (Economy Edition is not supported).

  2. Attach a VPC to the ACR EE instance so FC Agent Sandbox can pull images over VPC.

Image requirements

Use a Linux system based on the AMD64 architecture. Recommended base images: Ubuntu 20.04, Debian 12 (bookworm) or later.

Push the image

Push the image to that ACR EE repository and use the VPC-accessible internal image address, for example:

test-registry-vpc.cn-beijing.cr.aliyuncs.com/runtime/python:3.12

Build the template

Install dependencies:

python3 -m venv .venv
source .venv/bin/activate
pip install e2b==2.31.0 e2b-code-interpreter==2.8.1 python-dotenv

Create a .env file:

# Replace with your own API_KEY and image address
E2B_API_KEY=e2b_xxx
FROM_IMAGE="test-registry-vpc.cn-beijing.cr.aliyuncs.com/runtime/python:3.12"

# Beijing production environment example
E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com

Run the script to build the image into a template and create a sandbox to verify:

#!/usr/bin/env python3

import os
import time

from dotenv import load_dotenv
from e2b import Template, default_build_logger
from e2b_code_interpreter import Sandbox


load_dotenv()

FROM_IMAGE = os.getenv("FROM_IMAGE", "").strip()
RUN_CODE = "print('hello')"

# The SDK reads E2B_API_KEY / E2B_API_URL / E2B_DOMAIN automatically.
build = Template.build(
    Template().from_image(FROM_IMAGE),
    name=f"template-{int(time.time())}",
    cpu_count=2,
    memory_mb=2048,
    skip_cache=False,
    on_build_logs=default_build_logger(),
)
sandbox = Sandbox.create(template=build.template_id, timeout=900)

try:
    print(f"template_id: {build.template_id}")
    print(f"build_id: {build.build_id}")
    print(f"sandbox_id: {sandbox.sandbox_id}")
    print(f"sandbox_domain: {sandbox.sandbox_domain}")
    print(f"envd_api_url: {sandbox.envd_api_url}")

    execution = sandbox.run_code(RUN_CODE, timeout=60, request_timeout=120)
    stdout = "".join(execution.logs.stdout or [])
    stderr = "".join(execution.logs.stderr or [])

    print(f"run_code code: {RUN_CODE}")
    print(f"run_code stdout: {stdout.strip()}")
    print(f"run_code stderr: {stderr.strip()}")
    print(f"run_code error: {execution.error}")

    if execution.error is not None:
        raise RuntimeError(f"run_code failed: {execution.error}")
    if stdout.strip() != "hello":
        raise RuntimeError(f"run_code stdout unexpected: {stdout!r}")
finally:
    print(f"killing sandbox: {sandbox.sandbox_id}")
    sandbox.kill()
    print("sandbox killed")

TypeScript example:

import { Sandbox, Template, defaultBuildLogger } from "@e2b/code-interpreter";

// The SDK reads E2B_API_KEY / E2B_API_URL / E2B_DOMAIN automatically.
const build = await Template.build(
  Template().fromImage(process.env.FROM_IMAGE),
  `template-${Date.now()}`,
  {
    cpuCount: 2,
    memoryMB: 2048,
    skipCache: false,
    onBuildLogs: defaultBuildLogger(),
  },
);

const sandbox = await Sandbox.create(build.templateId, {
  timeoutMs: 900_000,
});

try {
  console.log(`template_id: ${build.templateId}`);
  console.log(`build_id: ${build.buildId}`);
  console.log(`sandbox_id: ${sandbox.sandboxId}`);

  const execution = await sandbox.runCode("print('hello')", {
    timeoutMs: 60_000,
    requestTimeoutMs: 120_000,
  });

  console.log(`run_code stdout: ${execution.logs.stdout.join("").trim()}`);
  console.log(`run_code stderr: ${execution.logs.stderr.join("").trim()}`);
  console.log("run_code error:", execution.error);

  if (execution.error) {
    throw new Error(`run_code failed: ${execution.error.value}`);
  }
} finally {
  await sandbox.kill();
}

Notes

Use official FC E2B images

FC E2B provides official images that do not require your own ACR EE instance. You can build a template and create a sandbox directly:

Reuse the Python script from the quick start section and use the following image address:

FROM_IMAGE="fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/code-interpreter-v1:v0.0.31"

The current FC E2B official image addresses for the Beijing region:

fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/base:v0.0.31
fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/code-interpreter-v1:v0.0.31

Use CLI to view templates and create sandboxes

If you have already installed the E2B CLI, you can check template build status with the template list command:

export E2B_API_KEY=e2b_xxx
export E2B_ACCESS_TOKEN=$E2B_API_KEY
export E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
export E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com

e2b template list

After the template status shows ready, you can create a sandbox using the template name or template_id:

e2b sandbox create my-code-interpreter-v1

Verify key dependencies after entering the sandbox:

env | sort | head
python3 --version
which python3

ACR EE network requirements

Before using your own ACR EE images, confirm the following conditions:

  • The ACR EE instance is attached to at least one VPC.

  • The VPC contains at least one vSwitch in an availability zone supported by Function Compute.

  • The ACR EE repository, VPC, vSwitch, and FC Agent Sandbox are in the same region. The examples in this document use the Beijing region.

  • The ACR EE access control and VPC configuration allow traffic from the corresponding network.

  • The VPC CIDR block uses private address ranges defined by RFC 1918: 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16. Public IP reuse is not supported. For details, see VPC FAQ.

  • The VPC has at least one security group that is not managed by a cloud service, and its rules allow access to the corresponding ACR EE instance.

The availability zones supported by Function Compute may change by region and product capability. For the latest list, see Function Compute supported availability zones.

Template naming best practices

Include the business name, base image, key dependency versions, or date in the template name, for example agent-python313-20260531. In production, avoid overwriting templates that are in use — create a new template and validate it with a canary rollout first.

Advanced configuration: adjust template builds via headers

sandbox-gateway supports passing X-E2B-Template-* extension headers through Template.build(..., headers={...}). You only need to configure these headers when you need to explicitly specify the build mode, target image, private registry credentials, or ACR EE network settings.

The builder is used to process a regular business image into an image suitable for FC Agent Sandbox templates. During the build, the platform temporarily starts an FC function that pulls the source image, adds the dependencies required by FC Agent Sandbox, and pushes the target image. The template then uses this target image to create sandbox runtime environments.

Example:

headers = {
    "X-E2B-Template-Build-Mode": "builder",
    "X-E2B-Template-Source-Registry-Type": "acree",
    "X-E2B-Template-Dest-Image-Ref": "example-registry.cn-beijing.cr.aliyuncs.com/example/app:e2b",
    "X-E2B-Template-Source-Username": "source-user",
    "X-E2B-Template-Source-Password": "source-password",
    "X-E2B-Template-Dest-Username": "dest-user",
    "X-E2B-Template-Dest-Password": "dest-password",
    "X-E2B-Template-Source-ACREE-Instance-ID": "cri-example",
    "X-E2B-Template-Source-VPC-ID": "vpc-example",
    "X-E2B-Template-Source-VSwitch-IDs": "vsw-example-a,vsw-example-b",
    "X-E2B-Template-Source-Security-Group-ID": "sg-example",
}

build = Template.build(
    Template().from_image(image),
    name=name,
    cpu_count=2,
    memory_mb=2048,
    skip_cache=False,
    on_build_logs=default_build_logger(),
    headers=headers,
)

Supported headers:

HeaderValue or FormatDescription
X-E2B-Template-Build-Modebuilder, directBuild mode. builder uses a temporary FC function to generate a target image adapted for FC Agent Sandbox; direct uses the source image directly.

In builder mode, the following additional headers can also be configured:

HeaderValue or FormatDescription
X-E2B-Template-Source-Registry-Typeacr, acreeSource image registry type.
X-E2B-Template-Dest-Image-RefFull image addressTarget image address.
X-E2B-Template-Source-UsernameStringSource image pull username.
X-E2B-Template-Source-PasswordStringSource image pull password or token.
X-E2B-Template-Dest-UsernameStringTarget image push username.
X-E2B-Template-Dest-PasswordStringTarget image push password or token.
X-E2B-Template-Source-ACREE-Instance-IDACR EE instance IDSource ACR EE instance ID.
X-E2B-Template-Source-VPC-IDVPC IDVPC used to access the source image repository.
X-E2B-Template-Source-VSwitch-IDsvSwitch ID list, comma-separatedvSwitches used to access the source image repository.
X-E2B-Template-Source-Security-Group-IDSecurity group IDSecurity group used to access the source image repository.
X-E2B-Template-Alpha-RegistryConfig-CertConfig-Insecuretrue, falseIgnore image registry certificate errors.
X-E2B-Template-Alpha-RegistryConfig-NetworkConfig-VpcIdVPC IDVPC ID of the self-managed image registry.
X-E2B-Template-Alpha-RegistryConfig-NetworkConfig-VSwitchIdvSwitch IDvSwitch ID of the self-managed image registry.
X-E2B-Template-Alpha-RegistryConfig-NetworkConfig-SecurityGroupIdSecurity group IDSecurity group ID of the self-managed image registry.

Build mode descriptions:

  • builder: Uses a temporary FC function to process the source image, add FC Agent Sandbox runtime dependencies, and generate a target image adapted for FC Agent Sandbox. Suitable for regular business images.

  • direct: Does not perform image conversion; uses the source image directly as a custom-container template function image. The source image must already include E2B runtime dependencies.

Notes:

  • Sensitive information such as passwords and tokens should only be read from .env or environment variables. Do not write them to the code repository or print them in logs.

  • The VPC, vSwitch, and security group headers are only used by the builder to access the source image repository. They do not affect the final template or sandbox network configuration.

Troubleshooting

1. Slow template build

First check your ACR EE image size, network path, image layer cache, and ACR EE private network configuration. Larger base images typically result in slower first builds.

If you only need to verify the template build pipeline, use an existing E2B-compatible image for comparison. These images already have envd and other runtime dependencies injected, making it easier to rule out image adaptation issues.

2. ACR EE image pull failure

Check the image address, region, namespace, repository permissions, VPC binding, and access control configuration. When using a private ACR EE image, network configuration errors are more common than SDK parameter errors.

3. vSwitch in unsupported zone

If you encounter vSwitch is in unsupported zone during build or runtime, the selected vSwitch is in an availability zone not supported by Function Compute.

Resolution:

  1. Check the current vSwitch availability zone from the error message.

  2. Select a zone from the Function Compute supported availability zones.

  3. Create a new vSwitch in that zone under the same VPC.

  4. Use this new vSwitch for Function Compute or related network configuration.

  5. Rebuild the template and create a sandbox to verify.

vSwitches in different availability zones within the same VPC are interconnected by default over the internal network. Therefore, even if business resources are in other availability zones, you can add a vSwitch under a Function Compute-supported availability zone within the same VPC to complete the Function Compute network integration.

4. Sandbox created successfully but run_code fails

run_code invokes the python3 command in the image to execute code. If the image does not include python3 or related dependencies, execution may fail. First verify whether the image contains the dependencies required by the code interpreter. You can run in the sandbox:

python3 --version
which python3
env | sort | head -50