> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/server/it/knowledge-base/how-to-articles/install-devolutions-server-for-linux.md).

# Installare Devolutions Server per Linux

Installi Devolutions Server per Linux con Bash e PowerShell su un database SQL Server o PostgreSQL, con la configurazione TLS, gli aggiornamenti e la rimozione tramite systemd.

Devolutions Server è disponibile per Linux con Microsoft Kestrel come server web integrato e Microsoft PowerShell 7 per l'installazione da riga di comando. Il database può essere Microsoft SQL Server o PostgreSQL. Questo argomento mostra come installare manualmente Devolutions Server per Linux con prompt Bash e script PowerShell, e come accedervi, aggiornarlo e rimuoverlo.

In alternativa, Devolutions Server può essere installato automaticamente utilizzando gli script disponibili nel [repository Devolutions GitHub ScriptLibrary](https://github.com/Devolutions/ScriptLibrary/tree/main/DVLSForLinux).

### Installazione dei prerequisiti <a href="#installing-prerequisites" id="installing-prerequisites"></a>

Devolutions Server necessita di un server di database. Installi il motore di database da usare con la procedura SQL Server o PostgreSQL, oppure passi direttamente all'installazione con PowerShell se il server di database esiste già.

#### SQL Server

1. Se Microsoft SQL Server non è già installato, esegua il seguente prompt Bash modificando la variabile `MSSQL_SA_PASSWORD` con una password complessa:

   ```bash
   source /etc/os-release
   curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor --batch --yes -o /usr/share/keyrings/microsoft-prod.gpg
   curl -fsSL https://packages.microsoft.com/config/ubuntu/$VERSION_ID/mssql-server-2022.list | sudo tee /etc/apt/sources.list.d/mssql-server-2022.list
   sudo apt-get update
   sudo apt-get install -y mssql-server
   sudo MSSQL_PID="evaluation" MSSQL_SA_PASSWORD="mystrongpassword" /opt/mssql/bin/mssql-conf -n setup accept-eula
   sudo /opt/mssql/bin/mssql-conf set sqlagent.enabled true
   sudo systemctl restart mssql-server
   ```

   In questo esempio `MSSQL_PID` è impostato su ***evaluation***, ma è possibile inserire qui una chiave prodotto.

{% hint style="warning" %}
Microsoft supporta solo [alcune versioni di SQL](https://docs.devolutions.net/server/it/overview-of-devolutions-server/system-requirements.md#software-dependencies). Consulti la documentazione di Microsoft per assicurarsi che la sua versione di SQL sia ufficialmente supportata per la sua distribuzione.
{% endhint %}

#### PostgreSQL

Devolutions Server supporta PostgreSQL 14 o successivo, installato su un server o fornito da un servizio PostgreSQL gestito che concede l'attributo `SUPERUSER`. Devolutions Server si connette con un unico ruolo, tramite un nome utente e una password: l'autenticazione integrata non è disponibile con PostgreSQL.

1. Se PostgreSQL non è già disponibile, lo installi sul server di database con questo prompt Bash:

   ```bash
   sudo apt-get update
   sudo apt-get install -y postgresql
   psql --version
   ```

   La versione di PostgreSQL fornita dalla distribuzione dipende dalla sua release. Si assicuri che la versione installata sia PostgreSQL 14 o successiva.
2. Crei un ruolo dedicato proprietario del database di Devolutions Server, con l'attributo `SUPERUSER` necessario per creare lo schema del database. Sostituisca `YOURSTRONGPASSWORD` con una password complessa:

   ```bash
   sudo -u postgres psql -c "CREATE ROLE dvls_owner LOGIN SUPERUSER PASSWORD 'YOURSTRONGPASSWORD';"
   sudo -u postgres psql -c "CREATE DATABASE dvls OWNER dvls_owner;"
   ```

   La creazione dello schema modifica le conversioni di tipo di PostgreSQL, operazione che solo un superutente può eseguire. Con un servizio PostgreSQL gestito, crei il ruolo e il database con l'account amministratore del servizio. Dopo l'installazione, il ruolo non richiede l'attributo `SUPERUSER`: lo rimuova con `sudo -u postgres psql -c "ALTER ROLE dvls_owner NOSUPERUSER;"`.
3. Sul computer che esegue Devolutions Server, installi gli strumenti client di PostgreSQL. Il processo di backup del database integrato di Devolutions Server esegue `pg_dump` e `pg_restore` e le procedure di aggiornamento e rimozione di questa pagina li usano:

   ```bash
   sudo apt-get install -y postgresql-client
   pg_dump --version
   ```

   La versione principale di `pg_dump` deve essere uguale o successiva alla versione principale del server PostgreSQL, altrimenti il backup non riesce. Quando il pacchetto della distribuzione è più vecchio del server, installi il pacchetto `postgresql-client-<major version>` corrispondente dal repository APT di PostgreSQL.

#### PowerShell e il modulo Devolutions.PowerShell

1. Esegua questo prompt Bash per installare PowerShell 7:

   ```bash
   sudo apt-get update
   sudo apt-get install -y wget apt-transport-https software-properties-common
   source /etc/os-release
   wget -q https://packages.microsoft.com/config/ubuntu/$VERSION_ID/packages-microsoft-prod.deb
   sudo dpkg -i packages-microsoft-prod.deb
   rm packages-microsoft-prod.deb
   sudo apt-get update
   sudo apt-get install -y powershell
   ```

   Esegua questo prompt da una directory in cui l'utente corrente può scrivere, poiché `wget` scarica il pacchetto `.deb` nella directory corrente.
2. Installi il [modulo Devolutions.PowerShell](https://www.powershellgallery.com/packages/Devolutions.PowerShell/) per tutti gli utenti (percorso: `/opt/microsoft/powershell/7/Modules`). Le procedure di installazione e aggiornamento di questa pagina eseguono PowerShell come root, che trova solo i moduli installati per tutti gli utenti:

   ```powershell
   & sudo pwsh -Command { Install-Module -Name 'Devolutions.PowerShell' -Confirm:$False -Scope 'AllUsers' -Force }
   ```

   È probabile che compaia un avviso che indica che l'installazione proviene da un repository non attendibile. Il modulo è ospitato in PowerShell Gallery, la posizione ufficiale di hosting dei moduli PowerShell gestita da Microsoft. Per non vedere più questo avviso, esegua `Set-PSRepository -Name PSGallery -InstallationPolicy Trusted`.
3. Crei un utente e un gruppo per Devolutions Server. Un utente e un gruppo separati sono facoltativi e isolano Devolutions Server dagli altri servizi. Questo prompt Bash crea un utente e un gruppo entrambi denominati ***dvls***, con la directory di installazione impostata su `/opt/devolutions/dvls`:

   ```bash
   sudo useradd -N dvls
   sudo groupadd dvls
   sudo usermod -a -G dvls dvls
   # optional, add current user to dvls group
   sudo usermod -a -G dvls $(id -un)
   sudo mkdir -p /opt/devolutions/dvls
   sudo chown -R dvls:dvls /opt/devolutions/dvls
   sudo chmod 550 /opt/devolutions/dvls
   ```

### Download e installazione di Devolutions Server for Linux <a href="#downloading-and-installing-dvls-for-linux" id="downloading-and-installing-dvls-for-linux"></a>

La directory di installazione appartiene a `dvls:dvls` in modalità 550, quindi l'installazione viene eseguita come root. Avvii PowerShell con `sudo pwsh` ed esegua tutti gli script PowerShell di questa sezione in quella sessione.

1. Scarichi la versione più recente di Devolutions Server per Linux ed estragga il file `.tar.gz` in `/opt/devolutions/dvls`:

   ```powershell
   Import-Module -Name 'Devolutions.PowerShell'

   $DVLSPath = '/opt/devolutions/dvls'
   $DVLSDownloadPath = '/tmp/dvls-linux-x64.tar.gz'

   Get-DPSProduct -Name 'DPSLinuxX64bin' -Destination $DVLSDownloadPath
   & tar -xzf $DVLSDownloadPath -C $DVLSPath --strip-components=1
   Remove-Item -Path $DVLSDownloadPath

   & chown -R dvls:dvls $DVLSPath
   & chmod -R o-rwx $DVLSPath
   & chmod 660 (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')
   & chmod 770 (Join-Path -Path $DVLSPath -ChildPath 'App_Data')

   Set-Location -Path $DVLSPath
   ```
2. Generi un certificato se Devolutions Server deve rispondere tramite TLS e non esiste ancora alcun certificato. Sostituisca `MYHOST` con il nome host del server:

   ```powershell
   & openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout cert.key -out cert.crt -subj "/CN=MYHOST" -addext "subjectAltName=DNS:MYHOST"
   & openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt -passout pass:
   ```

   `subjectAltName` usa `DNS:` in questo esempio. Per rispondere solo su un indirizzo IP, usi invece `IP:`. Il certificato `.pfx` generato non ha una password.

#### Parametri di installazione per SQL Server

Definisca i parametri di installazione nella stessa sessione di PowerShell. Sostituisca `MYHOST`, `MYEMAIL`, `MSSQLHOST`, `DBUSERNAME` e `YOURSTRONGPASSWORD` con i valori dell'ambiente. `MSSQLHOST` è l'host SQL Server, `localhost` quando SQL Server è in esecuzione sullo stesso computer. Per rispondere tramite TLS, usi `https` in `$DVLSURI`.

```powershell
$DVLSPath = '/opt/devolutions/dvls'
$DVLSURI  = 'http://MYHOST:5000/'

$DVLSAdminUsername = 'dvls-admin'
$DVLSAdminPassword = 'dvls-admin'
$DVLSAdminEmail    = 'MYEMAIL'

$Params = @{
    'DatabaseHost'           = 'MSSQLHOST'
    'DatabaseName'           = 'DSERVER'
    'DatabaseUserName'       = 'DBUSERNAME'
    'DatabasePassword'       = 'YOURSTRONGPASSWORD'
    'ServerName'             = 'DSERVER'
    'AccessUri'              = $DVLSURI
    'HttpListenerUri'        = $DVLSURI
    'DPSPath'                = $DVLSPath
    'UseEncryptedConnection' = $False # Modify as needed
    'TrustServerCertificate' = $False # Modify as needed
    'EnableTelemetry'        = $True  # Modify as needed
    'DisableEncryptConfig'   = $True
}
```

#### Parametri di installazione per PostgreSQL

Definisca i parametri di installazione nella stessa sessione di PowerShell. Sostituisca `MYHOST`, `MYEMAIL`, `PGHOST` e `YOURSTRONGPASSWORD` con i valori dell'ambiente. `PGHOST` è l'host PostgreSQL, `localhost` quando PostgreSQL è in esecuzione sullo stesso computer. Per rispondere tramite TLS, usi `https` in `$DVLSURI`.

```powershell
$DVLSPath = '/opt/devolutions/dvls'
$DVLSURI  = 'http://MYHOST:5000/'

$DVLSAdminUsername = 'dvls-admin'
$DVLSAdminPassword = 'dvls-admin'
$DVLSAdminEmail    = 'MYEMAIL'

$Params = @{
    'DatabaseType'         = 'PostgreSql'
    'DatabaseHost'         = 'PGHOST'
    'DatabasePort'         = 5432
    'DatabaseName'         = 'dvls'
    'DatabaseUserName'     = 'dvls_owner'
    'DatabasePassword'     = 'YOURSTRONGPASSWORD'
    'ServerName'           = 'DSERVER'
    'AccessUri'            = $DVLSURI
    'HttpListenerUri'      = $DVLSURI
    'DPSPath'              = $DVLSPath
    'EnableTelemetry'      = $True # Modify as needed
    'DisableEncryptConfig' = $True
}
```

`DatabasePort` è 5432 per impostazione predefinita quando viene omesso. Usi un nome di database in minuscolo: l'installazione crea il database con il nome tra virgolette, quindi il nome distingue maiuscole e minuscole nei comandi PostgreSQL.

Con `DatabaseType` impostato su `PostgreSql`, `New-DPSInstallConfiguration` ignora i parametri di SQL Server `-IntegratedSecurity`, `-FailoverPartner`, `-RetryCount` e `-RetryInterval` e visualizza un avviso quando vengono specificati. Anche `-UseEncryptedConnection` e `-TrustServerCertificate` non si applicano: la stringa di connessione usa `SSL Mode=Prefer`, che crittografa la connessione solo quando il server PostgreSQL offre TLS. Per richiedere la crittografia, cambi `SSL Mode` in `Require` o `VerifyFull` nelle stringhe di connessione di `appsettings.json` dopo l'installazione, quindi riavvii Devolutions Server.

La stringa di connessione conserva le parole chiave di PostgreSQL (`Host=`, `Port=`, `Database=`, `Username=`, `Password=`), ed è così che Devolutions Server rileva il motore PostgreSQL. È memorizzata in `ConnectionStrings.LocalSqlServer` in `appsettings.json`, la stessa chiave usata con SQL Server. Devolutions Server aggiunge `Search Path=dbo,public` e `Keep Alive=30` quando non sono specificati. Quando imposta `Search Path` manualmente, conservi `dbo` al suo interno, poiché tutte le tabelle di Devolutions Server sono nello schema `dbo`.

#### Esecuzione dell'installazione

1. Esegua l'installazione di Devolutions Server con il modulo Devolutions.PowerShell, nella stessa sessione di PowerShell:

   ```powershell
   $Configuration = New-DPSInstallConfiguration @Params
   New-DPSAppSettings -Configuration $Configuration

   $Settings = Get-DPSAppSettings -ApplicationPath $DVLSPath
   $ConnectionString = $Settings.ConnectionStrings.LocalSqlServer

   New-DPSDatabase -ConnectionString $ConnectionString
   Update-DPSDatabase -ConnectionString $ConnectionString -InstallationPath $DVLSPath
   New-DPSWorkspaceSettings -ConnectionString $ConnectionString

   New-DPSEncryptConfiguration -ApplicationPath $DVLSPath
   New-DPSDatabaseAppSettings -Configuration $Configuration

   New-DPSAdministrator -ConnectionString $ConnectionString -Name $DVLSAdminUsername -Password $DVLSAdminPassword -Email $DVLSAdminEmail
   ```

   `New-DPSDatabase` visualizza un avviso e continua quando il database esiste già, il che si verifica quando il database è stato creato in precedenza. `Update-DPSDatabase` crea quindi lo schema.
2. Se è stato generato un certificato, modifichi il file `appsettings.json` per consentire a Kestrel di rispondere tramite TLS:

   ```powershell
   $JSON = Get-Content -Path (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json') | ConvertFrom-JSON -Depth 100

   $JSON.Kestrel.Endpoints.Http | Add-Member -MemberType NoteProperty -Name 'Certificate' -Value @{
       'Path'     = (Join-Path -Path $DVLSPath -ChildPath 'cert.pfx')
       'Password' = ''
   }

   $JSON | ConvertTo-JSON -Depth 100 | Set-Content -Path (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')

   $AccessUri = (Get-DPSAccessUri -ConnectionString $ConnectionString).AccessUri
   Set-DPSAccessUri -ApplicationPath $DVLSPath -ConnectionString $ConnectionString -AccessURI ($AccessUri -Replace '^http:', 'https:')
   ```
3. Riapplichi la proprietà e le autorizzazioni dei file creati dall'installazione, quindi chiuda la sessione di PowerShell di root:

   ```powershell
   & chown -R dvls:dvls $DVLSPath
   & chmod -R o-rwx $DVLSPath
   & chmod 550 $DVLSPath
   & chmod 660 (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')
   & chmod 770 (Join-Path -Path $DVLSPath -ChildPath 'App_Data')
   exit
   ```
4. Crei un file di unità systemd per eseguire Devolutions Server per Linux in background e lo abiliti all'avvio, con questo prompt Bash:

   ```bash
   sudo tee /etc/systemd/system/dvls.service > /dev/null <<EOT
   [Unit]
   Description=Devolutions Server

   [Service]
   Type=simple
   Restart=always
   RestartSec=10
   User=dvls
   ExecStart=/opt/devolutions/dvls/Devolutions.Server
   WorkingDirectory=/opt/devolutions/dvls
   KillSignal=SIGINT
   SyslogIdentifier=dvls
   Environment="SCHEDULER_EMBEDDED=true"

   [Install]
   WantedBy=multi-user.target
   EOT

   sudo systemctl daemon-reload
   sudo systemctl enable dvls
   ```

   `SCHEDULER_EMBEDDED=true` esegue la pianificazione di Devolutions Server all'interno del servizio. Con PostgreSQL, il processo di backup integrato cerca `pg_dump` e `pg_restore` nel `PATH` del servizio. Se sono installati altrove, aggiunga `Environment="DVLS_PG_DUMP_PATH=/path/to/pg_dump"` e `Environment="DVLS_PG_RESTORE_PATH=/path/to/pg_restore"` alla sezione `[Service]`.
5. Avvii Devolutions Server e visualizzi il suo stato:

   ```bash
   sudo systemctl start dvls
   sudo systemctl status dvls
   ```

### Accedere a Devolutions Server for Linux <a href="#accessing-dvls-linux" id="accessing-dvls-linux"></a>

Devolutions Server per Linux è in ascolto sulla porta dell'`HttpListenerUri` impostato durante l'installazione, sull'indirizzo IP o sul nome host del sistema di installazione, ad esempio `http://MYHOST:5000`. Al primo avvio possono verificarsi errori OAuth quando si accede a Devolutions Server da un URL non configurato. In tal caso, aggiunga URI aggiuntivi su cui restare in ascolto oppure modifichi quello principale eseguendo lo script seguente in PowerShell:

```powershell
Import-Module -Name 'Devolutions.PowerShell'

$DVLSPath = '/opt/devolutions/dvls'

$Settings = Get-DPSAppSettings -ApplicationPath $DVLSPath
$ConnectionString = $Settings.ConnectionStrings.LocalSqlServer

Get-DPSAccessUri -ConnectionString $ConnectionString

Set-DPSAccessUri -ConnectionString $ConnectionString -ApplicationPath $DVLSPath -AccessURI 'http://10.10.0.20:5000/' -AdditionalAccessURIs @('http://ubuntu-2204:5000/')
```

Se Devolutions Server resta inaccessibile all'esterno del sistema installato, si assicuri che il firewall consenta la porta, ad esempio con Uncomplicated Firewall: `sudo ufw allow 5000`.

### Importare la chiave di crittografia di Devolutions Server <a href="#importing-devolutions-server-encryption-key" id="importing-devolutions-server-encryption-key"></a>

Quando l'installazione Linux usa il database di un'installazione Windows esistente, necessita delle chiavi di crittografia di quell'installazione.

**Esportazione da un'installazione Windows esistente**

```powershell
Import-Module -Name 'Devolutions.PowerShell'
$existingDVLSInstance = 'C:\my\path\dvlsInstance\'
$destination = 'C:\other\path\encryption.config'
Export-DPSEncryptionKeys -ApplicationPath $existingDVLSInstance -Destination $destination
```

**Importazione nella nuova installazione Linux**

```powershell
Import-Module -Name 'Devolutions.PowerShell'
$DVLSPath = '/opt/devolutions/dvls'
$keysToImport = '/path/to/encryption.config'
Import-DPSEncryptionKeys -ApplicationPath $DVLSPath -Filename $keysToImport
```

Quando le chiavi sono state esportate con `-Password`, aggiunga lo stesso `-Password` a `Import-DPSEncryptionKeys`.

### Aggiornare Devolutions Server for Linux <a href="#updating-devolutions-server-for-linux" id="updating-devolutions-server-for-linux"></a>

Non estragga il nuovo archivio `.tar.gz` direttamente sopra `/opt/devolutions/dvls`. In questo modo si sostituisce `appsettings.json`, che contiene le stringhe di connessione e le impostazioni di Kestrel, e restano i file della versione precedente, il che impedisce l'avvio del servizio. Segua sempre il metodo di aggiornamento descritto in questa pagina.

#### Backup del database

Esegua il backup del database prima dell'aggiornamento.

Con SQL Server, esegua `sqlcmd` dal pacchetto `mssql-tools18`, su Linux o verso un SQL Server remoto:

```bash
/opt/mssql-tools18/bin/sqlcmd -S <MSSQLHOST> -U <DBUSERNAME> -P '<PASSWORD>' -C \
  -Q "BACKUP DATABASE [DSERVER] TO DISK = N'/var/opt/mssql/data/DSERVER-$(date +%F-%H%M).bak' WITH INIT, COMPRESSION;"
```

Il percorso completo di `sqlcmd` evita l'errore "command not found" nelle shell che non sono di accesso, in cui `/etc/profile.d/mssql-tools.sh` non è stato caricato. `-C` considera attendibile il certificato del server, il che è necessario per le installazioni locali di SQL Server che usano un certificato autofirmato. La directory di backup deve essere scrivibile dall'utente `mssql`: `/var/opt/mssql/data/` funziona subito. Si assicuri che il file `.bak` esista e non sia vuoto prima di continuare.

Con PostgreSQL, esegua `pg_dump` con il ruolo del database, quindi convalidi l'archivio con `pg_restore --list`:

```bash
sudo mkdir -p /var/backups/dvls
sudo chown $(id -un) /var/backups/dvls
BACKUP_FILE=/var/backups/dvls/dvls-$(date +%F-%H%M).backup
pg_dump --format=custom --host=<PGHOST> --port=5432 --username=dvls_owner --dbname=dvls --file=$BACKUP_FILE
pg_restore --list $BACKUP_FILE > /dev/null && echo "Backup is valid: $BACKUP_FILE"
```

`pg_dump` chiede la password del ruolo. L'archivio contiene solo il database: esegua il backup delle chiavi di crittografia separatamente, poiché un backup del database non può essere usato senza di esse.

#### Aggiornamento dell'installazione

1. Arresti il servizio di Devolutions Server:

   ```bash
   sudo systemctl stop dvls.service
   sudo systemctl status dvls.service   # confirm inactive (dead)
   ```
2. Esegua il backup dei file di installazione e di configurazione. `/opt/devolutions/dvls` è in modalità 550 e appartiene a `dvls:dvls`, quindi i cmdlet di backup devono essere eseguiti come root. Avvii PowerShell con `sudo pwsh`, esegua questo script e tenga aperta la sessione per il resto dell'aggiornamento:

   ```powershell
   Import-Module -Name 'Devolutions.PowerShell'
   $DVLSPath      = '/opt/devolutions/dvls'
   $BackupBase    = "/var/backups/dvls/$(Get-Date -Format 'yyyy-MM-dd-HHmm')"
   $BackupConfig  = Join-Path -Path $BackupBase -ChildPath 'config'
   $BackupInstall = Join-Path -Path $BackupBase -ChildPath 'installation'
   New-Item -ItemType Directory -Path $BackupConfig, $BackupInstall -Force | Out-Null
   Backup-DPSConfigurationFiles -ApplicationPath $DVLSPath -BackupConfigurationPath $BackupConfig
   Backup-DPSInstallationFiles  -ApplicationPath $DVLSPath -BackupPath $BackupInstall
   ```

   `Backup-DPSConfigurationFiles` copia `App_Data/encryption.config`, `appsettings.json` e `web.config` quando esiste, e non riesce se manca `encryption.config`. `Backup-DPSInstallationFiles` copia l'intera directory di installazione e richiede una directory di destinazione vuota.
3. Scarichi la nuova versione, svuoti la directory di installazione tranne `App_Data`, che contiene `encryption.config` e lo stato di runtime, quindi estragga la nuova versione:

   ```powershell
   $DVLSDownloadPath = '/tmp/dvls-linux-x64.tar.gz'
   Get-DPSProduct -Name 'DPSLinuxX64bin' -Destination $DVLSDownloadPath
   Get-ChildItem -Path $DVLSPath -Force | Where-Object { $_.Name -ne 'App_Data' } | Remove-Item -Recurse -Force
   & tar -xzf $DVLSDownloadPath -C $DVLSPath --strip-components=1
   Remove-Item -Path $DVLSDownloadPath
   ```
4. Ripristini le cartelle personalizzate e la configurazione:

   ```powershell
   Restore-DPSCustomFolders          -BackupPath $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSAnomalyDetectionFolder -BackupPath $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSConfigurationFiles     -BackupConfigurationPath $BackupConfig -ApplicationPath $DVLSPath
   ```

   `Restore-DPSConfigurationFiles` unisce il `appsettings.json` salvato, comprese le stringhe di connessione, nel `appsettings.json` della nuova versione e copia il `encryption.config` salvato in `App_Data`.
5. Aggiorni lo schema del database con la stringa di connessione del `appsettings.json` ripristinato:

   ```powershell
   $ConnectionString = (Get-DPSAppSettings -ApplicationPath $DVLSPath).ConnectionStrings.LocalSqlServer
   Update-DPSDatabase -ConnectionString $ConnectionString -InstallationPath $DVLSPath
   ```

   `Update-DPSDatabase` funziona con le stringhe di connessione di SQL Server e di PostgreSQL. Non stampa nulla in caso di esito positivo e visualizza l'avviso `Update failed.` in caso di errore.
6. Riapplichi la proprietà e le autorizzazioni:

   ```powershell
   & chown -R dvls:dvls $DVLSPath
   & chmod -R o-rwx $DVLSPath
   & chmod 550 $DVLSPath
   & chmod 660 (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')
   & chmod 770 (Join-Path -Path $DVLSPath -ChildPath 'App_Data')
   # If a certs directory is in use:
   if (Test-Path -Path (Join-Path -Path $DVLSPath -ChildPath 'certs')) { & chmod 750 (Join-Path -Path $DVLSPath -ChildPath 'certs') }
   ```
7. Avvii il servizio e si assicuri che funzioni correttamente:

   ```powershell
   & systemctl start dvls.service
   & systemctl status dvls.service --no-pager
   & journalctl -u dvls.service -n 100 --no-pager
   ```

   Il journal mostra voci ***Migration done with status Done*** e nessuna riga `[ERR]` quando l'aggiornamento è riuscito.

#### Risoluzione dei problemi <a href="#troubleshooting" id="troubleshooting"></a>

* **Il servizio non si avvia, `appsettings.json` manca o è vuoto:** copi `$BackupConfig/appsettings.json` in `/opt/devolutions/dvls`, riapplichi la proprietà e le autorizzazioni, quindi avvii il servizio.
* **L'accesso funziona, ma le voci non si decrittografano:** `encryption.config` non è stato ripristinato. Copi `$BackupConfig/encryption.config` in `/opt/devolutions/dvls/App_Data/`, ne imposti il proprietario e la modalità con `chown dvls:dvls` e `chmod 660`, quindi riavvii il servizio.
* **Errori di schema del database in fase di esecuzione:** `Update-DPSDatabase` è stato saltato o non è riuscito. Esegua di nuovo `Update-DPSDatabase` con la stringa di connessione di `appsettings.json`.
* **Ripristino completo:** arresti il servizio, svuoti `/opt/devolutions/dvls` tranne `App_Data`, copi di nuovo il contenuto di `$BackupInstall` in `/opt/devolutions/dvls`, riapplichi la proprietà e le autorizzazioni, ripristini il database dal backup eseguito prima dell'aggiornamento e quindi avvii il servizio. Con SQL Server, ripristini il file `.bak` con `sqlcmd` e `RESTORE DATABASE [DSERVER] FROM DISK = N'<backup file>' WITH REPLACE;`. Con PostgreSQL, ripristini l'archivio con `pg_restore --clean --if-exists --single-transaction --host=<PGHOST> --username=dvls_owner --dbname=dvls <backup file>`. Se i ruoli del server di destinazione differiscono da quelli dell'origine, aggiunga `--no-owner --role=dvls_owner`.

### Manutenzione del database PostgreSQL <a href="#postgresql-database-maintenance" id="postgresql-database-maintenance"></a>

Una base de datos PostgreSQL utilizada por Devolutions Server necesita el siguiente mantenimiento:

* **Autovacuum:** mantenga autovacuum activado, que es el valor predeterminado de PostgreSQL.
* **Estadísticas:** ejecute `ANALYZE;` en la base de datos de Devolutions Server una vez después de la instalación y después de las importaciones grandes, por ejemplo `psql --host=<PGHOST> --username=dvls_owner --dbname=dvls -c "ANALYZE;"`.
* **Índices:** PostgreSQL no necesita los trabajos de reconstrucción y reorganización de índices que se usan con SQL Server. Si la hinchazón de los índices se acumula con el tiempo, ejecute `REINDEX CONCURRENTLY` en el índice afectado.
* **Programación:** PostgreSQL no tiene un equivalente de SQL Server Agent. Programe las tareas de mantenimiento personalizadas con cron.
* **Consultas:** los identificadores del esquema de Devolutions Server están en minúsculas en PostgreSQL. En `psql`, consulte `dbo.connections`, no `dbo.Connections`.

### Rimuovere Devolutions Server <a href="#removing-dvls" id="removing-dvls"></a>

Detenga y quite el servicio, el directorio de instalación y el usuario y el grupo ***dvls*** ejecutando este script en PowerShell, adaptado al sistema:

```powershell
& sudo systemctl stop dvls.service
& sudo systemctl disable dvls.service
& sudo rm /etc/systemd/system/dvls.service
& sudo systemctl daemon-reload
& sudo rm -rf /opt/devolutions/dvls
& sudo userdel -r dvls
& sudo groupdel dvls
```

A continuación, elimine la base de datos de Devolutions Server.

#### Eliminazione del database SQL Server

Questo script PowerShell si basa sul [modulo PowerShell DbaTools](https://dbatools.io/) per eliminare il database. Presuppone che `localhost` sia l'installazione di SQL Server e che `DSERVER` sia il nome del database:

```powershell
Import-Module dbatools
$Credential = Get-Credential

Set-DbaToolsInsecureConnection

Remove-DbaDatabase -SqlInstance localhost -SqlCredential $Credential -Database 'DSERVER' -Confirm:$False
```

#### Eliminazione del database PostgreSQL

Esegua `dropdb` con il ruolo proprietario del database oppure con un ruolo amministratore:

```bash
dropdb --host=<PGHOST> --port=5432 --username=dvls_owner dvls
```

`DROP DATABASE dvls;` in `psql` produce lo stesso risultato, da una connessione a un altro database come `postgres`. Per eliminare anche il ruolo, esegua `DROP ROLE dvls_owner;` con un ruolo amministratore.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.devolutions.net/server/it/knowledge-base/how-to-articles/install-devolutions-server-for-linux.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
