Skip to main content

Upgrade

Beginner
Tutorial

Overview

Unlike a canister reinstall that preserves the canister identifier but no state, a canister upgrade enables you to preserve the state of a deployed canister, and change the code.

For example, assume you have a dapp that manages professional profiles and social connections. If you want to add a new feature to the dapp, you need to be able to update the canister code without losing any of the previously-stored data. A canister upgrade enables you to update existing canister identifiers with program changes without losing the program state.

To preserve state when you are upgrading a canister written in Motoko, be sure to use the stable keyword to identify the variables you want to preserve. For more information about preserving variable state in Motoko, see stable variables and upgrade methods. If you are upgrading a canister written in Rust, you should use pre_upgrade and post_upgrade functions as illustrated in the Rust CDK asset storage example to ensure data is properly preserved after a canister upgrade.

To upgrade a canister:

  • Step 1: Open a new terminal and navigate to your project directory.

  • Step 2: Start the local canister execution environment, if necessary.

    In most cases, this step is only necessary if you are running the canisters locally.

    If you were registering canisters to run on a remote execution environment, e.g. ICP blockchain, you would include the --network command-line option to perform tasks on the environment specified under this parameter.

  • Step 3: Verify you have canister identifiers for all of the canisters you want to upgrade.

    Note that your program must identify the variables for which to maintain state by using the stable keyword in the variable declaration.

    For more information about declaring stable variables, see the Motoko documentation.

  • Step 4: Upgrade all of the canisters by running the following command:

      dfx canister install --all --mode upgrade