Access OSS through PrivateLink

更新时间:
复制 MD 格式

PrivateLink establishes a secure, private connection between your VPC and Alibaba Cloud OSS. This provides network-level traffic isolation to mitigate data security risks, resolve network address conflicts, and reduce operational complexity, helping you build a secure and controllable cloud storage access architecture.

How it works

PrivateLink works by creating a dedicated private endpoint in your VPC that connects to Alibaba Cloud OSS. This ensures that all access traffic remains within the Alibaba Cloud backbone network and does not traverse the public internet. It also provides precise, source-IP-based access control and VPC flow logs for auditing, creating an enterprise-grade data security framework. Compared to the default internal domain names that OSS provides, PrivateLink offers a higher level of native network security isolation and fine-grained control, making it suitable for the following business scenarios:

Business scenario

Internal domain name

PrivateLink

Strict security and compliance requirements

Access is through a public service entry point, exposing the attack surface to all VPCs. Security relies mainly on application-layer policies.

Reduces the attack surface. The entry point is inside your VPC, so other VPCs cannot discover or access it. Traffic is natively isolated at the network layer.

Need for fine-grained, network-level access control

You cannot use a security group to control access to OSS. You can only rely on a bucket policy.

Supports security group binding. You can configure security group rules for a PrivateLink endpoint to precisely control which source IPs can access OSS.

Need to audit all network connection attempts

OSS access logs only record successful requests. They cannot audit rejected network-layer connection attempts.

Supports VPC flow logs. You can capture and audit all traffic that attempts to access the endpoint, regardless of success.

Complex hybrid cloud network architecture with potential IP conflicts

Cloud services use the 100.64.0.0/10 CIDR block by default, which may conflict with your on-premises data center network plan.

Avoids IP conflicts. The endpoint uses an IP address from your VPC's CIDR block, fully adhering to your custom IP plan and simplifying hybrid cloud routing.

Supported regions

China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Heyuan), China (Guangzhou), China (Chengdu), Hong Kong (China), Japan (Tokyo), South Korea (Seoul), Singapore, Indonesia (Jakarta), Thailand (Bangkok), Germany (Frankfurt), US (Silicon Valley), US (Virginia), and UK (London).

Configure and use PrivateLink

Create an endpoint to establish a private connection through PrivateLink, enabling secure access to OSS resources from your VPC or on-premises data center.

Create and verify an endpoint

First, create an endpoint to establish a secure, private connection between your VPC and OSS. After the endpoint is created, use an ECS instance to verify its network connectivity and access OSS to verify that the configuration is correct.

Before you begin, ensure that you have created a VPC and a vSwitch. The verification steps require an ECS instance. If you do not have an existing instance, see Purchase an ECS instance to create a pay-as-you-go instance.

Step 1: Create an endpoint

  1. Go to the VPC endpoint page and click Create Endpoint. If this is your first time using the service, follow the on-screen prompts to activate the PrivateLink service.

  2. Configure the following parameters and keep the default values for any unlisted options.

    • Region: Select the region where the target OSS bucket is located, for example, China (Hangzhou).

    • Endpoint Name: Enter a descriptive name for the endpoint, such as privatelink-oss.

    • Endpoint Type: Select Interface Endpoint.

    • Endpoint Service: Select Alibaba Cloud Service, and then select the OSS endpoint service from the list (the entry whose name ends with oss).

    • VPC: Select the target VPC where you want to create the endpoint. If no VPC is available, click Create VPC to create a new one.

    • Security Groups: Select the security group to bind to the endpoint to control access permissions. If no suitable security group is available, click Create Security Group to create one.

    • Zone and vSwitch: Select the availability zone and corresponding vSwitch for the endpoint deployment. If no vSwitch is available, click Create vSwitch to create a new one.

  3. Click OK. The system automatically creates the endpoint. After creation, you can view and copy the Domain Name of Endpoint Service on the endpoint details page. Use this domain name for subsequent OSS access.

    The domain name of the endpoint service is in the format ep-<InstanceID>.oss.cn-hangzhou.privatelink.aliyuncs.com. In the Domain name of endpoint service section, click Copy to obtain it.

Step 2: Verify the endpoint

Run a connectivity test and download a file to confirm that the PrivateLink endpoint is configured correctly.

  • Verify network connectivity

    Use the ping command to test network connectivity to the endpoint domain name and confirm that DNS resolution and the network path are correct.

    ping -c 4 ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com
  • Verify file download

    From an ECS instance in the same region, use ossutil to download a file over the PrivateLink connection and confirm that data transfer works end-to-end.

    1. Install and configure ossutil 2.0.

    2. Use the endpoint domain name (for example, ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com) to access OSS resources. The following example downloads a file named dest.jpg from a bucket named example-bucket:

      ossutil cp oss://example-bucket/dest.jpg /tmp/ -e ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com --addressing-style path

      A successful command displays the following output, indicating that the file was downloaded. You can view the downloaded file in the /tmp directory.

      Success: Total 1 object, size 134102 B, Download done:(1 files, 134102 B), avg 680.112 KiB/s
      0.193189(s) elapsed

Strengthen VPC access security

After you verify the PrivateLink functionality, you can further enhance security by configuring a bucket policy. The following example shows how to restrict access to allow requests only from the VPC bound to the PrivateLink endpoint. This implements access control at both the network and application layers.

  1. Go to the Bucket list and click the target bucket.

  2. In the left-side navigation pane, click Permission Control > Bucket Policy.

  3. Click Authorize and configure the following settings. You can keep the default options for other parameters.

    • Authorized User: Select All Accounts (*).

    • Authorized Operation: Select Advanced Settings.

    • Effect: Select Reject.

    • Actions: Select oss:GetObject.

    • Condition: Select VPC ≠ and choose the VPC bound to your PrivateLink endpoint from the drop-down list.

  4. Click OK to complete the bucket policy configuration.

Connect local devices using SSL-VPN

The SSL-VPN solution lets individual local devices, such as developer workstations or mobile devices, connect to your VPC through an encrypted tunnel. After a device establishes a tunnel, it can securely access OSS using the configured PrivateLink endpoint. This approach is suitable for remote work, development and testing, and emergency access scenarios.

Step 1: Create SSL-VPN gateway and configure client

Deploy an SSL-VPN gateway and complete the client configuration to establish an encrypted connection between your local device and the VPC. For detailed configuration steps, see Connect a PC or an Android device to a VPC by using an SSL-VPN connection.

Step 2: Verify PrivateLink access to OSS

Verify the PrivateLink connection by running a connectivity test and downloading a file to ensure the private access link is functional.

  • Verify connectivity

    Use the ping command to test network connectivity to the endpoint domain name and verify that DNS resolution and the network path are correct.

    ping -c 4 ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com
  • Verify file download

    ossutil

    Use ossutil to verify the connection by performing a file operation.

    1. Install and configure ossutil 2.0.

    2. Use the endpoint domain name (for example, ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com) to access OSS resources. The following example downloads a file named dest.jpg from a bucket named example-bucket:

      ossutil cp oss://example-bucket/dest.jpg /tmp/ -e ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com --addressing-style path

      A successful command displays the following output, indicating that the file was downloaded. You can view the downloaded file in the /tmp directory.

      Success: Total 1 object, size 134102 B, Download done:(1 files, 134102 B), avg 680.112 KiB/s
      0.193189(s) elapsed

    SDK

    Using an SDK more closely resembles a production environment, supporting complex business logic integration and exception handling. The following SDKs support accessing OSS through PrivateLink.

    Java

    When accessing OSS through PrivateLink, call setSLDEnabled(true) to enable path-style access mode. For public network access, set it to setSLDEnabled(false).

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.model.GetObjectRequest;
    import java.io.File;
    /**
     * OSS PrivateLink access example
     * Demonstrates how to access OSS and download a file by using PrivateLink
     */
    public class Test {
        public static void main(String[] args) throws Exception {
            // PrivateLink endpoint domain name.
            String endpoint = "https://ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com";
            // Specify the region that corresponds to the endpoint, for example, cn-hangzhou.
            String region = "cn-hangzhou";
            // Obtain credentials from environment variables.
            // Before running, set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
            EnvironmentVariableCredentialsProvider credentialsProvider =
                    CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the bucket name, for example, example-bucket.
            String bucketName = "example-bucket";
            // Specify the full path of the object, excluding the bucket name.
            String objectName = "dest.jpg";
            // Specify the local file name.
            String pathName = "dest.jpg";
            // Configure client parameters.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            // Enable path-style access for PrivateLink access. Set to false for public access via the bucket's internet domain name.
            clientBuilderConfiguration.setSLDEnabled(true);
            // Explicitly declare the use of the Signature Version 4 algorithm.
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            // Create an OSS client instance.
            OSS ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
            try {
                // Download the object to a local file.
                // If the specified local file exists, it will be overwritten. If not, it will be created.
                // If no local path is specified, the downloaded file is saved by default to the project's root directory.
                ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
            } catch (OSSException oe) {
                // Handle OSS server-side exceptions.
                System.out.println("Caught an OSSException, which means your request made it to the OSS server, but was rejected with an error response.");
                System.out.println("Error Message: " + oe.getErrorMessage());
                System.out.println("Error Code: " + oe.getErrorCode());
                System.out.println("Request ID: " + oe.getRequestId());
                System.out.println("Host ID: " + oe.getHostId());
            } catch (ClientException ce) {
                // Handle client-side exceptions.
                System.out.println("Caught a ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, " +
                        "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
            } finally {
                // Release resources.
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

    Python

    When accessing OSS through PrivateLink, set is_path_style=True to enable path-style access mode.

    # -*- coding: utf-8 -*-
    """
    OSS PrivateLink access example
    Accesses OSS via PrivateLink and downloads a file locally.
    """
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    def main():
        """Main function: Demonstrates accessing OSS and downloading a file via PrivateLink."""
        # Configure access credentials.
        # Note: An Alibaba Cloud account's AccessKey has all API permissions and carries high risk.
        # We strongly recommend creating and using a RAM user for API access or daily O&M. Log in to the RAM console to create a RAM user.
        auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
        # PrivateLink endpoint domain name.
        endpoint = 'https://ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com'
        # Bucket name.
        bucket_name = 'example-bucket'
        # Create a Bucket object.
        # is_path_style=True enables path-style access mode, which is suitable for scenarios like PrivateLink.
        bucket = oss2.Bucket(auth, endpoint, bucket_name, is_path_style=True)
        # OSS object path (full path excluding the bucket name).
        object_name = 'dest.jpg'
        # Local path to save the file.
        local_file_path = 'dest.jpg'
        # Download the object to a local file.
        # If the specified local file exists, it will be overwritten. If not, a new file will be created.
        bucket.get_object_to_file(object_name, local_file_path)
        print(f"File downloaded successfully: {object_name} -> {local_file_path}")
    if __name__ == '__main__':
        main()      

    Go

    When accessing OSS through PrivateLink, use ForcePathStyle(true) to enable path-style access mode.

    package main
    import (
    	"fmt"
    	"os"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    const (
    	// PrivateLink endpoint domain name.
    	endpoint = "https://ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com"
    	// Bucket name.
    	bucketName = "example-bucket"
    	// OSS object path (full path excluding the bucket name).
    	objectName = "dest.jpg"
    	// Local path to save the file.
    	localFilePath = "dest.jpg"
    )
    func main() {
    	// Initialize the access credentials provider.
    	// Obtain credentials from environment variables.
    	// Before running this code example, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Printf("Failed to initialize credentials provider: %v\n", err)
    		os.Exit(-1)
    	}
    	// Create an OSS client instance.
    	// oss.ForcePathStyle(true) enables path-style access mode, which is suitable for scenarios like PrivateLink.
    	client, err := oss.New(
    		endpoint,
    		"", // AccessKeyId is obtained through the credentials provider.
    		"", // AccessKeySecret is obtained through the credentials provider.
    		oss.SetCredentialsProvider(&provider),
    		oss.ForcePathStyle(true),
    	)
    	if err != nil {
    		fmt.Printf("Failed to create OSS client: %v\n", err)
    		os.Exit(-1)
    	}
    	// Get the Bucket object.
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		fmt.Printf("Failed to get Bucket object: %v\n", err)
    		os.Exit(-1)
    	}
    	// Download the object to a local file.
    	// If the specified local file exists, it will be overwritten. If not, a new file will be created.
    	// If no local path is specified, the downloaded file is saved by default to the project's root directory.
    	err = bucket.GetObjectToFile(objectName, localFilePath)
    	if err != nil {
    		fmt.Printf("Failed to download file: %v\n", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("File downloaded successfully: %s -> %s\n", objectName, localFilePath)
    }
    

    C++

    When accessing OSS through PrivateLink, set conf.isPathStyle = true to enable path-style access mode.

    #include <alibabacloud/oss/OssClient.h>
    #include <memory>
    #include <fstream>
    #include <iostream>
    using namespace AlibabaCloud::OSS;
    int main(void)
    {
        // PrivateLink endpoint domain name.
        std::string Endpoint = "https://ep-bp1i****************.oss.cn-hangzhou.privatelink.aliyuncs.com";
        // Bucket name.
        std::string BucketName = "example-bucket";
        // OSS object path (must not include the bucket name).
        std::string ObjectName = "dest.jpg";
        // Local path to save the file.
        // If the specified local file exists, it will be overwritten. If not, a new file will be created.
        // If no local path is specified, the downloaded file is saved by default to the project's root directory.
        std::string FileNametoSave = "dest.jpg";
        // Initialize OSS SDK resources.
        InitializeSdk();
        // Configure client parameters.
        ClientConfiguration conf;
        // Obtain credentials from environment variables.
        // Before running this code example, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
        // Enable path-style access mode, which is suitable for scenarios like PrivateLink.
        conf.isPathStyle = true;
        // Create an OSS client instance.
        OssClient client(Endpoint, credentialsProvider, conf);
        // Build the GetObject request.
        GetObjectRequest request(BucketName, ObjectName);
        // Set the response stream factory to create a local file stream.
        request.setResponseStreamFactory([=]() {
            return std::make_shared<std::fstream>(
                FileNametoSave, 
                std::ios_base::out | std::ios_base::in | std::ios_base::trunc | std::ios_base::binary
            );
        });
        // Execute the download operation.
        auto outcome = client.GetObject(request);
        // Process the download result.
        if (outcome.isSuccess()) {
            std::cout << "File downloaded successfully. Size: " 
                      << outcome.result().Metadata().ContentLength() 
                      << " bytes" << std::endl;
            std::cout << "File saved to: " << FileNametoSave << std::endl;
        }
        else {
            // Handle errors.
            std::cout << "File download failed" << std::endl
                      << "Error code: " << outcome.error().Code() << std::endl
                      << "Error message: " << outcome.error().Message() << std::endl
                      << "Request ID: " << outcome.error().RequestId() << std::endl;
            // Release resources and return an error code.
            ShutdownSdk();
            return -1;
        }
        // Release OSS SDK resources.
        ShutdownSdk();
        return 0;
    }

Connect data centers with Express Connect or VPN

An on-premises data center can connect to an Alibaba Cloud VPC through an Express Connect circuit or a VPN gateway, and then use PrivateLink to access OSS over a private network. Express Connect provides stable network performance and guaranteed bandwidth, while a VPN gateway offers a flexible, encrypted connection. Both solutions are suitable for large-scale data transfer in production environments. For detailed configuration methods, see Connect a VPC to an on-premises data center or another cloud.

Production environment

Best practices

  • Optimize security group configurations

    Configure security group rules based on the principle of least privilege. Open endpoint access ports only to necessary IP address ranges and establish a regular security rule review mechanism. Precise source IP and port controls ensure that access policies align with business requirements, preventing permission sprawl and unauthorized access.

  • Monitor network connectivity

    Enable the VPC flow logs feature and establish an anomaly detection mechanism based on traffic patterns to monitor PrivateLink access behavior and data transfer status in real time.

  • Use a multi-AZ deployment

    In a production environment, deploy endpoints across multiple availability zones to build a highly available and fault-tolerant architecture. Use load balancing or DNS round-robin to distribute traffic. If an availability zone fails, traffic automatically switches to healthy endpoints in other zones, ensuring service continuity and business stability.

Billing

PrivateLink is billed hourly based on actual usage. Fees include an instance fee and a data processing fee. The service user and service provider can be different Alibaba Cloud accounts, and charges can be billed to a specified account. For more billing information, see Billing overview.