All Products
Search
Document Center

Object Storage Service:Create a ZRS bucket

Last Updated:Jan 29, 2024

Object Storage Service (OSS) supports zone-redundant storage (ZRS). ZRS stores multiple copies of your data across multiple zones in the same region. Your data is still accessible even if a zone becomes unavailable. ZRS provides 99.9999999999% (12 nines) data durability. This topic describes how to create a ZRS bucket.

Scenarios

ZRS provides disaster recovery at the data center level. Even if a data center becomes unavailable due to network disconnections, power outages, or other disasters, OSS maintains strong consistency. This way, services are not interrupted, and your data is not lost during failovers. This also helps meet strict requirements in key business systems whose recovery time objective (RTO) and recovery point objective (RPO) must be zero.

Usage notes

  • ZSR is supported in the following regions: China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Hong Kong), Japan (Tokyo), Singapore, Indonesia (Jakarta), and Germany (Frankfurt).

  • The unit cost of ZRS is higher than that of LRS. For more information, visit the OSS pricing page.

  • ZRS cannot be disabled after it is enabled.

Supported storage classes

ZRS supports the following storage classes: Standard, Infrequent Access (IA), and Archive. The following table describes the differences between the storage classes.

Item

Standard

IA

Archive

Designed data durability

99.9999999999% (12 nines)

99.9999999999% (12 nines)

99.9999999999% (12 nines)

Service availability

99.995%

99.50%

99.50%

Minimum billable object size

N/A

64 KB

64 KB

Minimum storage duration

N/A

30 days

60 days

Data retrieval fee

N/A

Based on the size (GB) of retrieved data

Based on the size (GB) of restored data or retrieved Archive data for real-time access

Data access

Real-time access with a latency of only milliseconds

Real-time access with a latency of only milliseconds

A one-minute restoration process required if real-time access of Archive objects is not enabled Real-time access with a latency of only milliseconds if real-time access of Archive objects is enabled

Image processing

Supported

Supported

Supported

Procedure

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, click Create Bucket.

  3. In the Create Bucket panel, select ZRS (Recommended) for Redundancy Type and configure the other parameters.

    For more information about the parameters, see Create a bucket.

Use OSS SDKs

The following sample code provides examples on how to enable ZRS when you create a bucket by using OSS SDKs for common programming languages. For information about how to use OSS SDKs for other programming languages to enable ZRS when you create a bucket, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        String endpoint = "yourEndpoint";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. 
        String bucketName = "examplebucket";
        // Specify the ID of the resource group. If you do not specify a resource group ID, the bucket belongs to the default resource group. 
        //String rsId = "rg-aek27tc****";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // Create a bucket and enable the hierarchical namespace feature for the bucket. 
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
            // The following code provides an example on how to specify the storage class, access control list (ACL), and redundancy type when you create the bucket. 
            // In this example, the storage class of the bucket is Standard. 
            createBucketRequest.setStorageClass(StorageClass.Standard);
            // The default redundancy type of the bucket is DataRedundancyType.LRS. 
            createBucketRequest.setDataRedundancyType(DataRedundancyType.LRS);
            // Set the ACL of the bucket to public-read. The default ACL is private. 
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            // When you create a bucket in a region that supports resource groups, you can configure a resource group for the bucket. 
            //createBucketRequest.setResourceGroupId(rsId);

            ossClient.createBucket(createBucketRequest);

            // Create a bucket. 
            ossClient.createBucket(createBucketRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            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) {
            System.out.println("Caught an 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 {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$accessKeyId = getenv("OSS_ACCESS_KEY_ID"); 
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    // Set the storage class of the bucket to Infrequent Access (IA). The default storage class is Standard. 
    $options = array(
        OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA
    );
    // Set the ACL of the bucket to public-read. The default bucket ACL is private. 
    $ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ, $options);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");        
const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET
});

// Create the bucket. 
async function putBucket() {
  try {
    const options = {
      storageClass: 'Standard', // By default, the storage class of a bucket is Standard. To set the storage class of the bucket to Archive, set storageClass to Archive. 
      acl: 'private', // By default, the access control list (ACL) of a bucket is private. To set the ACL of the bucket to public read, set acl to public-read. 
      dataRedundancyType: 'LRS' // By default, the redundancy type of a bucket is locally redundant storage (LRS). To set the redundancy type of the bucket to zone-redundant storage (ZRS), set dataRedundancyType to ZRS. 
    }
    // Specify the name of the bucket. 
    const result = await client.putBucket('examplebucket', options);
    console.log(result);
  } catch (err) {
    console.log(err);
  }
}

putBucket();        
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from the environment variables. Before you run this sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Create the bucket. 
# The following sample code provides an example on how to specify the storage class, access control list (ACL), and redundancy type when you create the bucket. 
# In this example, the storage class is Standard, the ACL is private, and the redundancy type is zone-redundant storage (ZRS). 
# bucketConfig = oss2.models.BucketCreateConfig(oss2.BUCKET_STORAGE_CLASS_STANDARD, oss2.BUCKET_DATA_REDUNDANCY_TYPE_ZRS)
# bucket.create_bucket(oss2.BUCKET_ACL_PRIVATE, bucketConfig)
bucket.create_bucket()
using Aliyun.OSS;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";

// Initialize an OssClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
// Create a bucket. 
try
    {
        var request = new CreateBucketRequest(bucketName);
        // Set the access control list (ACL) of the bucket to PublicRead. The default value is private. 
        request.ACL = CannedAccessControlList.PublicRead;
        // Set the redundancy type of the bucket to zone-redundant storage (ZRS). 
        request.DataRedundancyType = DataRedundancyType.ZRS;
        client.CreateBucket(request);
        Console.WriteLine("Create bucket succeeded");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create bucket failed. {0}", ex.Message);
    }
// Construct a request to create a bucket. 
// Specify the name of the bucket. 
CreateBucketRequest createBucketRequest = new CreateBucketRequest("examplebucket");
// Set the region in which the bucket is located to the China (Hangzhou) region. 
createBucketRequest.setLocationConstraint("oss-cn-hangzhou");
// Specify the access control list (ACL) of the bucket. 
// createBucketRequest.setBucketACL(CannedAccessControlList.Private);
// Specify the storage class of the bucket. 
// createBucketRequest.setBucketStorageClass(StorageClass.Standard);

// Create the bucket asynchronously. 
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
    @Override
    public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
        Log.d("asyncCreateBucket", "Success");
    }
    @Override
    public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientException != null) {
            // Handle client exceptions, such as network exceptions. 
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Handle service exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
package main

    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )

func main() {
    /// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create a bucket named examplebucket. Set the storage class to IA (oss.StorageIA), the ACL to public-read (oss.ACLPublicRead), and the redundancy type to ZRS (oss.RedundancyZRS). 
    err = client.CreateBucket("examplebucket", oss.StorageClass(oss.StorageIA), oss.ACL(oss.ACLPublicRead), oss.RedundancyType(oss.RedundancyZRS))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}
id<OSSCredentialProvider> credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:@"<StsServer>"];
OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
cfg.maxRetryCount = 3;
cfg.timeoutIntervalForRequest = 15;

// If an OSSClient instance is released, all tasks in the session are canceled and the session becomes invalid. Make sure that the OSSClient instance is not released before the request is complete. 
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
OSSClient *client = [[OSSClient alloc] initWithEndpoint:@"Endpoint" credentialProvider:credentialProvider clientConfiguration:cfg];

OSSCreateBucketRequest * create = [OSSCreateBucketRequest new];
// Set the bucket name to examplebucket. 
create.bucketName = @"examplebucket";
// Set the access control list (ACL) of the bucket to private. 
create.xOssACL = @"private";
// Set the storage class of the bucket to Infrequent Access (IA). 
create.storageClass = OSSBucketStorageClassIA;

OSSTask * createTask = [client createBucket:create];

[createTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"create bucket success!");
    } else {
        NSLog(@"create bucket failed, error: %@", task.error);
    }
    return nil;
}];            
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
    
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Specify the name, storage class, and access control list (ACL) of the bucket. */
    CreateBucketRequest request(BucketName, StorageClass::IA, CannedAccessControlList::PublicReadWrite);
    /* Set the redundancy type of the bucket to zone-redundant storage (ZRS). */
    //request.setDataRedundancyType(DataRedundancyType::ZRS);

    /* Create the bucket. */
    auto outcome = client.CreateBucket(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "CreateBucket fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";

void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */  
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    /* Specify whether to use CNAME to access OSS. The value of 0 indicates that CNAME is not used.  */
    options->config->is_cname = 0;
    /* Configure network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources.  */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value specifies that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    oss_acl_e oss_acl = OSS_ACL_PRIVATE;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    /* Assign char* data to a bucket of the aos_string_t type.  */
    aos_str_set(&bucket, bucket_name);
    /* Create the bucket. */
    resp_status = oss_create_bucket(oss_client_options, &bucket, oss_acl, &resp_headers);
    /* Determine whether the bucket is created.  */
    if (aos_status_is_ok(resp_status)) {
        printf("create bucket succeeded\n");
    } else {
        printf("create bucket failed\n");
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources.  */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket. 
client.create_bucket('examplebucket')

Use ossutil

You can use ossutil to create a ZRS bucket. For more information, see mb (create buckets).

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucket.