All Products
Search
Document Center

Container Service for Kubernetes:Modify cluster resources when restoring an application

Last Updated:Aug 27, 2026

Modify cluster resources during application restoration so that a backed-up application runs correctly in a different cluster environment, such as when you remap namespaces or change the image registry in a hybrid cloud scenario.

How resource modification works

When you back up cluster resources, by default, Backup Center performs a full backup of the runtime configuration at the time of the backup. During restoration, you might need to manually modify specific fields or configurations. For example, in a hybrid cloud scenario, different clusters might pull images from different image registries, so you must adjust the image address in the image field when you restore the application.

Resource modifications during restoration fall into three types, depending on how they are applied:

  • Default modifications — Applied automatically by the migrate-controller add-on during restoration. No configuration is required.

  • Common modifications — Applied by configuring specific fields in the restore task.

  • Custom modifications — Applied through the Resource Modifier feature of Velero. You create a ConfigMap that supports JSON Patch operations such as add, delete, and replace to change specified fields.

Use the following table to choose a modification method based on what you need to change:

What you need to modify

Modification method

Remove temporary information such as resource UIDs; convert Flexvolume to CSI when restoring volumes; upgrade API versions; apply known cross-cloud compatibility fixes

Default modifications

Remap namespaces; map StorageClass and image registry addresses; override Service and Ingress annotations for network plugin compatibility

Common modifications

Change other fields, such as a volume mount path or node affinity

Custom modifications

Limitations

Before you modify resources during restoration, review the following constraints of the Resource Modifier feature:

  • Permissions — The Resource Modifier feature is available only to users with cluster role-based access control (RBAC) administrator permissions, and it does not support modifying security-sensitive resource groups or fields. For more information about cluster RBAC administrator authorization, see Authorize operations on in-cluster resources with RBAC.

  • Volumes — By default, volume data uses dynamic volume provisioning during backup and restoration. The Container Storage Interface (CSI) plugin creates a new volume based on the specified StorageClass. Therefore, the Resource Modifier feature does not support modifying volumes in this scenario. If you need to modify volume configurations, consider changing the target StorageClass.

  • Cluster version — To modify resources by using the Resource Modifier feature, make sure that the restore cluster runs Kubernetes 1.20 or later and uses the CSI storage plugin.

Prerequisites

  • The migrate-controller add-on of version 1.8.1 or later is installed in both the backup cluster and the restore cluster. For more information, see Install migrate-controller and configure permissions.

  • A backup vault is created in the backup cluster. For more information, see Create a backup vault. The backup vault used in this topic has the following configuration:

Name

OSS bucket name

OSS bucket subdirectory

OSS bucket region

Scope

vault

cnfs-oss-test

subpath

China (Beijing)

Does not affect queries

Important

If the backup cluster, restore cluster, and backup vault are not in the same region, you must enable public network access for both the backup cluster and the restore cluster.

Example scenario

In this example, you back up an NGINX application and restore it to a different namespace and cluster. During restoration, you remap the namespace and image registry address through common modifications, and you use the Resource Modifier feature to change a volume mount path and remove node affinity.

A StatefulSet is deployed in the default namespace of the backup cluster. The image registry is provided by the OpenAnolis community at anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis. The application uses the volumeClaimTemplates field to automatically create cloud disk volumes with the alicloud-disk-topology-alltype StorageClass.

The following YAML shows the application configuration:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
  namespace: default
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  serviceName: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      affinity:
        nodeAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - preference:
              matchExpressions:
              - key: node-role.kubernetes.io/control-plane
                operator: Exists
            weight: 1
      containers:
      - image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          name: web
          protocol: TCP
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /usr/share/nginx/html/
          name: www
  volumeClaimTemplates:
  - apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      labels:
        app: nginx
      name: www
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 20Gi
      storageClassName: alicloud-disk-topology-alltype
      volumeMode: Filesystem

Run the following command to verify that the application and volumes are in a normal state:

kubectl get pod && kubectl get pvc

Expected output:

NAME    READY   STATUS    RESTARTS   AGE
web-0   1/1     Running   0          39s
web-1   1/1     Running   0          30s
NAME        STATUS   VOLUME                   CAPACITY   ACCESS MODES   STORAGECLASS                     VOLUMEATTRIBUTESCLASS   AGE
www-web-0   Bound    d-2zefofsg0uzoiaxxxxxx   20Gi       RWO            alicloud-disk-topology-alltype   <unset>                 3m18s
www-web-1   Bound    d-2zedgdlghw2oudxxxxxx   20Gi       RWO            alicloud-disk-topology-alltype   <unset>                 30s

Step 1: Back up the application in the backup cluster

Create an Instant Backup task by using either kubectl or the ACK console.

kubectl

  1. Create a file named applicationbackup.yaml in the backup cluster with the following content:

    apiVersion: csdr.alibabacloud.com/v1beta1
    kind: ApplicationBackup
    metadata:
      # If this backup vault has already been used in the cluster, the csdr.alibabacloud.com/backuplocations annotation can be omitted.
      annotations:
        csdr.alibabacloud.com/backuplocations: '{"name":"<backuplocationName>","region":"<bucketRegion>","bucket":"<bucketName>","prefix":"<path>","provider":"alibabacloud"}'
      name: <backupName>
      namespace: csdr
    spec:
      backupType: AppAndPvBackup
      includedNamespaces:
      - default
      pvBackup:
        defaultPvBackup: true
      storageLocation: <backuplocationName>
      ttl: 720h0m0s
  2. Run the following command in the backup cluster to deploy the ApplicationBackup task:

    kubectl apply -f applicationbackup.yaml
  3. Run the following command to check the backup task status and confirm that the status is Completed:

    kubectl -ncsdr get applicationbackup <backupName> --watch

    Expected output:

    NAME                                  PHASE       AGE
    <backupName>                          Completed   18s

Console

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the cluster name. In the left-side navigation pane, choose Operations > Application Backup. If prompted, install the backup service component. For registered and dedicated clusters, also configure permissions.

  3. On the Application Backup page, click Back up Now. In the Back up Now panel, configure the parameters for the backup, and then click OK. For more information about advanced configuration parameters, see Back up and restore applications in a cluster.

    Parameter

    Description

    Example

    Name

    The name of the Instant Backup task. This parameter is required.

    backup

    Backup Vaults

    (Required) The vault to store the backup in.

    cnfs-oss-test

    Backup Type

    Application Backup or Data Protection. See the backup plan table above for details.

    application backup

    Backup Namespaces

    (Required) One or more namespaces to back up. The kube-system, kube-publish, kube-node-lease, and csdr namespaces cannot be backed up.

    default

    Backup Volume

    Specifies whether to back up data in the volumes used by the application. Mounted Volumes backs up to ECS snapshots (disk volumes) or Cloud Backup (other types). Disable skips volume data and restores YAML only.

    Selected

  4. On the Application Backup page, go to the Backup Records tab. The Status column of the backup task shows Completed, which indicates that the backup was successful.

(Optional) Step 2: View the JSON files of backed-up resources in the OSS console

The JSON files of backed-up resources contain information about all backed-up resources, including the resource names, types, sizes, and creation dates. Check these files to verify that the backup includes the resources you want to restore. The following procedure uses the backup vault created in Prerequisites as an example to describe how to view the JSON files of backed-up resources in the Object Storage Service (OSS) console.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets, and then click the target bucket cnfs-oss-test.

  3. In the left-side navigation pane, choose Object Management > Objects.

    Navigate to the /subpath/backups/<backupName>/ path, find the compressed package named <backupName>.tar.gz, and then download and decompress the package to view the JSON files of all backed-up resources. Confirm that the extracted files include the resources you plan to restore.

Step 3: Initialize the backup vault in the restore cluster

Before you restore the application, initialize the backup vault in the restore cluster so that the cluster can access the backup data. Use the following backuplocation.yaml example to initialize the backup vault.

Note

If the backup vault is already initialized, skip this step.

apiVersion: csdr.alibabacloud.com/v1beta1
kind: BackupLocation
metadata:
  name: <backupVaultName>
  namespace: csdr
spec:
  backupSyncPeriod: 0s
  # The following configuration must match the one used when the backup vault was created. You can also initialize the backup vault in the restore cluster console.
  config:
    network: internal
    region: <ossBucketRegion>
  objectStorage:
    bucket: <ossBucketName>
    prefix: <ossBucketSubpath>
  provider: alibabacloud

Step 4: Define a custom resource modification policy in the restore cluster

A custom resource modification policy consists of two parts: conditions, which specifies the resources to modify, and patches, which specifies the fields and modification methods. In this example, the policy modifies both StatefulSet and Pod resources: it removes the node affinity configuration and changes the volume mount path in the container to /data.

  1. Create a file named resourcemodifier.yaml in the restore cluster with the following content:

    apiVersion: v1
    data:
      modifier: |
        version: v1
        resourceModifierRules:
        - conditions:
            groupResource: statefulsets.apps
            namespaces:
            - default
            labelSelector:
              matchLabels:
                app: nginx
          patches:
          - operation: remove
            path: "/spec/template/spec/affinity/nodeAffinity"
          - operation: replace
            path: "/spec/template/spec/containers/0/volumeMounts/0/mountPath"
            value: "/data"
        - conditions:
            groupResource: pods
            resourceNameRegex: "^web.*$"
            namespaces:
            - default
            labelSelector:
              matchLabels:
                app: nginx
          patches:
          - operation: remove
            path: "/spec/affinity"
          - operation: replace
            path: "/spec/containers/0/volumeMounts/0/mountPath"
            value: "/data"
    kind: ConfigMap
    metadata:
      name: <backupName>-resource-modifier
      namespace: csdr
  2. Run the following command to create the ConfigMap in the restore cluster:

    kubectl apply -f resourcemodifier.yaml
  3. Run the following command to confirm that the ConfigMap exists in the restore cluster:

kubectl -n csdr get configmap <backupName>-resource-modifier

The following table describes the conditions field:

Field

Description

Required

Example

groupResource

The Kubernetes resource group. Custom resource types defined by a CustomResourceDefinition (CRD) are supported. Format: <resourceName>.<groupName>. For resources in the core group, the group name can be omitted. You can run the kubectl api-resources command to query resource groups.

Yes

statefulsets.appspods

namespaces

The namespace of the resources to modify. If this field is left empty, the modification applies to resources in all namespaces. If namespace mapping is enabled, the original namespace applies.

No

default

labelSelector

The Kubernetes objects to modify. This field supports matchLabels and matchExpressions in the standard selector format, which is the same as the format used for applications such as Deployments. If this field is specified, the modification applies only to the selected resources.

No

matchLabels: {app: nginx}

resourceNameRegex

The regular expression that resource names must match. If this field is specified, the modification applies only to resources whose names match the expression.

No

"^web.*$"

The following table describes the patches field:

Field

Description

Required

Example

operation

The modification operation, such as add, remove, or replace.

Yes

replace

path

The path of the field to modify.

Yes

"/spec/template/spec/containers/0/volumeMounts/0/mountPath"

value

The new value after the modification. This field is supported only for add and replace operations.

No

"/data"

Step 5: Restore the modified application in the restore cluster

Create a restore task in the restore cluster to restore the modified application. The task includes the Step 4 defined in the previous step, and uses the namespaceMapping and imageRegistryMapping fields to configure mappings for namespaces and image registry addresses. Both fields use the Map format.

  1. Create a restore task file named applicationrestore.yaml based on the following example. In this example, resources (including volume data) backed up in the default namespace are restored to the default1 namespace. The OpenAnolis community image registry address is changed to a Container Registry (ACR) image registry address. Make sure that images are synchronized between the two registries before you change the registry address.

    apiVersion: csdr.alibabacloud.com/v1beta1
    kind: ApplicationRestore
    metadata:
      name: <restoreName>
      namespace: csdr
    spec:
      backupName: <backupName>
      namespaceMapping:
        default: default1   # Restore to the default1 namespace.
      imageRegistryMapping:
        anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis: registry.cn-beijing.aliyuncs.com/<acrRegistry>  # Make sure that images are synchronized between the two registries before the change.
      resourceModifier:
        kind: ConfigMap
        name: <backupName>-resource-modifier
  2. Run the following command in the restore cluster to deploy the ApplicationRestore task:

    kubectl apply -f applicationrestore.yaml
  3. Run the following command to check the status of the restore task:

kubectl -n csdr get applicationrestore <restoreName> --watch

Expected output:

NAME                                    PHASE       AGE
<restoreName>                           Completed   18h

The status of the restore task can also be checked in the console. For more information, see Restore applications and volumes.

Step 6: Verify that the application is restored as expected

Run the following command to retrieve the configuration of the restored StatefulSet:

kubectl -n default1 get sts web -oyaml

Expected output:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1","kind":"StatefulSet","metadata":{"annotations":{},"labels":{"app":"nginx"},"name":"web","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"nginx"}},"serviceName":"nginx","template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"affinity":{"nodeAffinity":{"preferredDuringSchedulingIgnoredDuringExecution":[{"preference":{"matchExpressions":[{"key":"node-role.kubernetes.io/master","operator":"Exists"}]},"weight":1}]}},"containers":[{"image":"anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.2","imagePullPolicy":"IfNotPresent","name":"nginx","ports":[{"containerPort":80,"name":"web","protocol":"TCP"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","volumeMounts":[{"mountPath":"/usr/share/nginx/html/","name":"www"}]}]}},"volumeClaimTemplates":[{"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"labels":{"app":"nginx"},"name":"www"},"spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"20Gi"}},"storageClassName":"alicloud-disk-topology-alltype","volumeMode":"Filesystem"}}]}}
  creationTimestamp: "2024-10-09T08:32:50Z"
  generation: 1
  labels:
    app: nginx
    velero.io/backup-name: <backupName>
    velero.io/restore-name: <restoreName>
  name: web
  namespace: default1
  resourceVersion: "119622"
  uid: d23878ea-0b9f-40ba-b61b-1ff6bb77eb43
spec:
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain
  podManagementPolicy: OrderedReady
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: nginx
  serviceName: nginx
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      affinity: {}
      containers:
      - image: registry.cn-beijing.aliyuncs.com/<acrRegistry>/nginx:1.14.1-8.6
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          name: web
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /data
          name: www
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
  updateStrategy:
    rollingUpdate:
      partition: 0
    type: RollingUpdate
  volumeClaimTemplates:
  - apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
      name: www
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 20Gi
      storageClassName: alicloud-disk-topology-alltype
      volumeMode: Filesystem
    status:
      phase: Pending
status:
  availableReplicas: 0
  collisionCount: 0
  currentRevision: web-7b454646b4
  observedGeneration: 1
  replicas: 2
  updateRevision: web-7b454646b4

In the expected output, the container image registry address, the mount path in the container, and the namespace have all been adjusted as specified. The node affinity configuration has been removed. Some new fields in the YAML output are automatically populated by Kubernetes.

The kubectl.kubernetes.io/last-applied-configuration annotation retains the original configuration from before the restore, so the values inside it can differ from the modified live specification.