VPC network configuration allows a sandbox to access resources in a virtual private cloud, such as RDS, Redis, NAS, private APIs, ACR EE registries, or self-managed services.
FC Agent Sandbox passes VPC settings through sandbox metadata. When you create a sandbox, serialize vpcId, securityGroupId, and vSwitchIds as a JSON string and write it to the reserved field fc.sandbox.network.vpc. The configuration takes effect for that sandbox creation and does not need to be baked into a template.
Prerequisites
Prepare the following before use:
FC Agent Sandbox API Key, and the
E2B_API_URLandE2B_DOMAINfor the current region.Target VPC ID.
At least one vSwitch ID. The vSwitch should be in a zone supported by Function Compute. If the target resource is in another zone, different vSwitches in the same VPC can usually communicate over the private network.
A security group ID that is not managed by a cloud service. Its outbound rules must allow the protocols and ports that the sandbox needs to access.
The private address and port of the target resource, such as an RDS private endpoint, NAS server address, Redis private endpoint, or private HTTP API.
If the target resource has an allowlist, such as an RDS allowlist or self-managed service access control, add the CIDR block of the selected vSwitch to the allowlist. Network reachability does not grant business permissions. Database accounts, API tokens, RAM roles, and similar permissions must still be configured separately.
VPC Metadata Format
The value of fc.sandbox.network.vpc must be a JSON string with this structure:
{
"vpcId": "vpc-xxxxxxxx",
"securityGroupId": "sg-xxxxxxxx",
"vSwitchIds": ["vsw-xxxxxxxx"]
}Field reference:
| Field | Required | Description |
vpcId | Yes | The VPC that the sandbox needs to join. |
securityGroupId | Yes | The security group associated with the sandbox. It controls outbound access. |
vSwitchIds | Yes | The vSwitch ID list. Configure two or more vSwitches when possible to improve availability and reduce the risk of exhausting IPs in one subnet. |
Create a Sandbox with VPC Configuration
The following example follows 08_vpc_config.py: pass VPC settings through metadata during sandbox creation, then run a command inside the sandbox to confirm that creation succeeded.
Set environment variables before running:
export E2B_API_KEY="<your-api-key>"
export E2B_API_URL="https://api.<region>.e2b.fc.aliyuncs.com"
export E2B_DOMAIN="<region>.e2b.fc.aliyuncs.com"
export E2E_VPC_ID="vpc-xxxxxxxx"
export E2E_SECURITY_GROUP_ID="sg-xxxxxxxx"
export E2E_VSWITCH_ID="vsw-xxxxxxxx"Python example:
import json
import os
from dotenv import load_dotenv
from e2b import Sandbox
load_dotenv()
vpc_config = {
"vpcId": os.environ["E2E_VPC_ID"],
"securityGroupId": os.environ["E2E_SECURITY_GROUP_ID"],
"vSwitchIds": [os.environ["E2E_VSWITCH_ID"]],
}
conn_opts = {
"api_key": os.environ["E2B_API_KEY"],
"timeout": 300,
}
if os.environ.get("E2B_API_URL"):
conn_opts["api_url"] = os.environ["E2B_API_URL"]
if os.environ.get("E2B_DOMAIN"):
conn_opts["domain"] = os.environ["E2B_DOMAIN"]
sandbox = Sandbox.create(
**conn_opts,
metadata={
"fc.sandbox.network.vpc": json.dumps(vpc_config),
},
)
try:
print(f"Sandbox created: {sandbox.sandbox_id}")
result = sandbox.commands.run("echo 'VPC config applied'")
print(result.stdout.strip())
finally:
sandbox.kill()If your workload needs a specific template, add template="code-interpreter-v1" or a custom template ID to Sandbox.create(). Keep the VPC configuration in metadata.
TypeScript example:
import { Sandbox } from "e2b";
function required(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`${name} is required`);
}
return value;
}
const vpcConfig = {
vpcId: required("E2E_VPC_ID"),
securityGroupId: required("E2E_SECURITY_GROUP_ID"),
vSwitchIds: [required("E2E_VSWITCH_ID")],
};
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: required("E2B_API_KEY"),
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
timeoutMs: 300_000,
metadata: {
"fc.sandbox.network.vpc": JSON.stringify(vpcConfig),
},
});
try {
const result = await sandbox.commands.run("echo 'VPC config applied'");
console.log(result.stdout.trim());
} finally {
await sandbox.kill();
}Verify Private Network Access
Successful creation only means that the control plane accepted the VPC configuration. Access a target address inside the VPC to verify data-plane reachability. The following example tests a TCP connection to a host and port. You can use it for NAS 2049, RDS 3306, Redis 6379, or a private HTTP service port.
Set these variables before running:
export E2E_INTERNAL_HOST="<internal-host-or-ip>"
export E2E_INTERNAL_PORT="3306"Run the reachability check inside the sandbox:
host = os.environ["E2E_INTERNAL_HOST"]
port = int(os.environ["E2E_INTERNAL_PORT"])
command = (
"python3 - <<'PY'\n"
"import socket\n"
f"host = {json.dumps(host)}\n"
f"port = {port}\n"
"try:\n"
" socket.create_connection((host, port), timeout=5).close()\n"
"except OSError as exc:\n"
" print(f'reachable=0 error={type(exc).__name__}: {exc}')\n"
"else:\n"
" print('reachable=1')\n"
"PY"
)
result = sandbox.commands.run(command, timeout=10)
print(result.stdout.strip())To prove that the VPC configuration is the reason access works, first create a sandbox without the fc.sandbox.network.vpc metadata and confirm that the same private address is unreachable. Then create a sandbox with the VPC metadata and confirm that the same address is reachable.
FAQ
| Symptom | Possible cause | Fix |
| Sandbox creation fails | vpcId, securityGroupId, or vSwitchIds does not exist, or the resources are not in the same region | Check the resource IDs, region, and account. |
| Creation succeeds but the private address is unreachable | Security group outbound rules do not allow the traffic, the target resource allowlist does not include the vSwitch CIDR block, or the target service is not listening on the port | Check security group outbound rules, target resource allowlists, and service listener status. |
| The vSwitch zone is unsupported | The vSwitch is in a zone that Function Compute does not support in the current region | Create a vSwitch in a Function Compute-supported zone in the same VPC and update vSwitchIds. |
| Creation or connection fails intermittently | The vSwitch subnet has too few available IPs, or only one zone is configured | Use a larger subnet or configure two or more vSwitches. |
| The workload needs both public internet and VPC access | Configuring a VPC does not imply a fixed public egress path. Public access depends on FC Agent Sandbox and Function Compute network policies | Confirm whether the workload needs public access, NAT, or a fixed public IP solution. |
Notes
fc.sandbox.network.vpcis a reserved metadata field used by FC Extensions. Ordinary business metadata does not change network configuration.The value of
fc.sandbox.network.vpcmust be a JSON string. Do not pass a Python dict or JavaScript object directly.The VPC, vSwitch, security group, FC Agent Sandbox, and target resources should be in the same region or in a reachable network scope.
Open only the ports and address ranges that the sandbox needs.
Do not expose long-lived credentials in code, templates, metadata, environment variables, or logs.