OneLinersCommand workbench
Guides
Packages & Updates / Incident Response & Troubleshooting / System Administration

Fix Sub-process /usr/bin/dpkg returned an error code (1) safely

Sub-process /usr/bin/dpkg returned an error code (1) is a final summary, not the root cause. The decisive message normally appears earlier in the transaction. This guide preserves that first failure, checks package-manager ownership, locks, disk and filesystem health, audits dpkg state, then completes configuration or performs a targeted rollback without deleting lock files or forcing unrelated removals.

40 min9 stepsChanges system stateRevision 1
Save or explore
Save to collectionCreate a collection in the sidebar first.
0 of 9 steps completed
Goal

Return Ubuntu package management to a consistent state with no active competing transaction, no half-configured packages, successful dpkg and APT consistency checks, and a recorded recovery path for the package that originally failed.

Supported environments
  • Ubuntu Server 22.04 LTS, 24.04 LTS, 26.04 LTS
  • dpkg 1.21 or newer
  • APT 2.4 or newer
Prerequisites
  • Console or recovery access Keep a second administrative session or console available. Package configuration can restart services or expose a boot-critical package failure.id; who; uptime
  • A maintenance window Do not repair package state while an automated update, image build, deployment, or another operator is changing packages.systemctl list-timers 'apt-*' --all
  • Enough storage for recovery APT and dpkg need writable space under /, /var, and /boot. Capture bytes and inodes before running a repair.df -hT / /var /boot 2>/dev/null; df -i / /var /boot 2>/dev/null
Operating boundary

OneLiners never runs these steps or stores secrets. Review placeholders, versions, current state, and change-control requirements before using a command.

Full guide

What you will build

System
  • A repeatable package-recovery workflow that starts from the first apt or dpkg failure, proves exclusive transaction ownership and host health, and bounds every repair with a simulation.
  • A clean package database with verified dependencies, an intentionally installed or removed failing package, healthy affected services, preserved evidence, and a documented rollback path.
Observable outcome
  • dpkg --audit and apt-get check complete without incomplete-package or dependency findings.
  • The originally failing package reaches a known ii state or is intentionally removed through a reviewed rollback, and its affected service or application passes a health check.
  • The next simulated upgrade is coherent and operators did not delete lock files, overwrite the package database, or hide the original failure.

Architecture

How the parts fit together

APT calculates repository candidates and dependency transactions, while dpkg owns the local package database, unpacking, maintainer scripts, triggers, and package states. systemd timers and unattended-upgrades may be legitimate transaction owners. Filesystems and package-specific services are external dependencies whose failures can surface only as dpkg error code 1.

APT front endResolves candidates and dependencies, downloads archives, presents transactions, and calls dpkg in the required order.
dpkg databaseRecords desired, current, and error states plus package files, conffiles, triggers, and maintainer scripts.
Transaction ownerA human shell, systemd apt timer, unattended-upgrades, installer, image builder, or deployment process that must hold package locks exclusively.
Host storageProvides writable space and inodes for archives, unpacking, logs, initramfs, package databases, and temporary script output.
Package maintainer scriptRuns package-specific preinst, postinst, prerm, or postrm actions and may validate configuration or control services.
  1. The requested APT action records its transcript and delegates local package operations to dpkg.
  2. dpkg unpacks files, runs configuration scripts and triggers, then records the new state.
  3. A script, dependency, lock, disk, filesystem, or repository failure stops the sequence and leaves one or more package records incomplete.
  4. The operator preserves the first failure, restores prerequisites, simulates dependency changes, and resumes only the recorded incomplete stage.
  5. Independent database, service, boot, and future-upgrade checks prove recovery.

Assumptions

  • The host is a supported Ubuntu release using apt and dpkg with repositories intentionally configured for that release.
  • The operator has sudo access, a maintenance window, console or secondary-session recovery, and authority to change the affected packages.
  • Package databases still exist and are readable; physical storage corruption or missing /var/lib/dpkg data requires a broader system recovery process.
  • Application data and custom configuration have their own backups; reinstalling a package is not treated as an application backup.
  • Any third-party repository is documented, signed, pinned, and approved before its package becomes part of a recovery transaction.

Key concepts

error code (1)
A generic failure result from the dpkg subprocess. It indicates that the transaction failed but does not identify why; the meaningful cause is normally earlier in output.
package state
dpkg records desired action, current state, and an error flag. Installed and configured packages normally report ii; unpacked or half-configured records require investigation.
maintainer script
Package-supplied code run during installation, configuration, upgrade, removal, or purge. It may change services and fail for application-specific reasons.
fix-broken
An APT dependency-repair mode that can propose installs or removals. It must be simulated and reviewed because it is not limited to one harmless action.
package lock
Exclusive ownership preventing concurrent package database writers. Removing a lock file does not terminate the process that holds the underlying lock.
conffile
A package-managed configuration file whose local modifications follow dpkg's preservation and prompt rules during upgrades or reinstalls.
Set guide values0/4 ready

Fill these once. Every matching command and configuration block updates immediately; values stay in this page only.

Security and production boundaries

  • Never delete dpkg or APT lock files to bypass an active writer. Stop or wait for the owning process through its service or automation controller.
  • Never replace /var/lib/dpkg/status with an arbitrary old copy or remove package database directories during ordinary error-code recovery.
  • Do not add --force-all, --force-conflicts, --allow-unauthenticated, or unaudited repository keys to make a blocked transaction proceed.
  • Maintainer scripts execute with root privileges. Treat unexpected third-party script behavior, package origin changes, and signature failures as security events.
  • Package logs can contain repository URLs, proxy information, hostnames, or application errors. Redact secrets while preserving the exact ordering and package names.

Stop before continuing if

  • Stop when another apt, dpkg, unattended-upgrades, installer, or automation process owns a package lock.
  • Stop on disk I/O errors, read-only mounts, package database corruption, zero inodes, or insufficient /boot space.
  • Stop if a simulated transaction removes essential, boot, remote-access, storage, database, or production workload packages unexpectedly.
  • Stop after the same maintainer script fails again; diagnose its first error instead of looping dpkg --configure -a.
  • Stop before rebooting when kernel, initramfs, bootloader, libc, systemd, dpkg, or apt configuration did not complete cleanly.
01

command

Preserve the first package error before retrying

read-only

The final dpkg error code only reports that one or more package actions failed. Capture the preceding APT terminal transcript and dpkg log around the failure. Search upward for the first maintainer-script, dependency, filesystem, signature, or configuration error rather than treating the final line as the diagnosis.

Why this step matters

Retried configuration can append new output, rotate logs, or obscure the first failure. Preserving the original sequence separates the root cause from dpkg's generic transaction summary.

What to understand

A maintainer script runs package-specific code and can fail because of application configuration, service startup, missing files, permissions, or external dependencies.

The first failing package may cause later dependency errors. Repair that cause before chasing every package printed near the end.

History logs show the requested transaction while term.log preserves the interactive output that named the failing script or command.

System changes

  • None. The commands read package-manager logs and do not start, configure, install, or remove packages.

Syntax explained

grep -B12 -A4
Shows context before and after each known error marker so the first cause is not detached from its package.
tail -n
Bounds output while keeping the newest transaction evidence.
sudo
Reads protected logs only; it does not grant a package tool permission to modify state.
Command
Fill variables0/1 ready

Values stay on this page and are never sent or saved.

sudo tail -n '{{logLines}}' /var/log/apt/term.log
sudo tail -n '{{logLines}}' /var/log/apt/history.log
sudo tail -n '{{logLines}}' /var/log/dpkg.log
sudo grep -B12 -A4 -E 'dpkg: error|dependency problems|No space left|read-only file system|returned an error code \(1\)' /var/log/apt/term.log | tail -n 80
Example output / evidence
Setting up example-daemon (2.4.1-1ubuntu1) ...
Job for example-daemon.service failed because the control process exited with error code.
dpkg: error processing package example-daemon (--configure):
 installed example-daemon package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 example-daemon
E: Sub-process /usr/bin/dpkg returned an error code (1)

Checkpoint: Name the first failing package and operation

sudo grep -B8 -A3 'returned an error' /var/log/apt/term.log | tail -n 40

Continue whenThe record identifies a package and action such as --configure before the final Sub-process /usr/bin/dpkg returned an error code (1).

Stop whenStop if logs are missing or the first cause remains unknown; reproduce only through a reviewed dry run or maintenance window.

If this step fails

The log contains only the final error code

Likely causeThe useful output was printed to another terminal, rotated, or discarded by automation.

Safe checks
  • journalctl --since '-2 hours' -p warning..alert
  • ls -lh /var/log/apt /var/log/dpkg.log*

ResolutionPreserve available system and automation logs, identify the exact transaction, and do not run broad repair commands until the failing package is known.

Security notes

  • Redact repository credentials, proxy URLs, customer hostnames, and application secrets before sharing logs.

Alternatives

  • Use the deployment or image-build log when apt ran inside automation and host logs do not contain the transaction.

Stop conditions

  • Do not continue if the first failure points to disk I/O errors, a read-only filesystem, or an unknown third-party maintainer script.
02

command

Check for an active package manager without deleting locks

read-only

A lock usually means another process owns the package database. Inspect processes, systemd units, and lock-file holders. Wait for a healthy active update to finish or stop the owning automation through its documented control path. Never remove lock files while apt or dpkg is running.

Why this step matters

Lock ownership protects the package database from concurrent writers. Deleting a lock does not stop its process and can permit overlapping transactions that corrupt package state.

What to understand

A recent apt-daily or unattended-upgrades process may be healthy. Check its start time and journal progress before deciding it is stuck.

A defunct process cannot hold a live file descriptor, but a parent service may still be restarting the transaction.

Use systemctl or the automation platform to stop a genuinely stuck owner only after preserving logs and confirming no package script is actively changing files.

System changes

  • None. Process, unit, and file-descriptor state are inspected without sending signals or deleting files.

Syntax explained

ps -eo
Prints process ancestry, start time, state, and full command for ownership analysis.
systemctl status
Shows whether scheduled APT services are active and includes recent journal messages.
fuser -v
Reports processes with open references to package-manager lock paths.
Command
ps -eo pid,ppid,lstart,stat,cmd | grep -E '[a]pt|[d]pkg|unattended-upgrade'
systemctl --no-pager --full status apt-daily.service apt-daily-upgrade.service unattended-upgrades.service 2>&1 | head -80
sudo fuser -v /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend /var/lib/apt/lists/lock /var/cache/apt/archives/lock 2>&1 || true
Example output / evidence
                     USER        PID ACCESS COMMAND
/var/lib/dpkg/lock:  root       1842 F.... dpkg
● apt-daily-upgrade.service - Daily apt upgrade and clean activities
     Active: activating (start) since Sun 2026-08-23 16:50:12 UTC; 3min ago

Checkpoint: Confirm exclusive maintenance ownership

sudo fuser /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend 2>/dev/null || true

Continue whenNo PID is printed before manual recovery begins.

Stop whenStop if any apt, dpkg, unattended-upgrades, installer, or image-build process is still active.

Security notes

  • Do not use kill -9 as a first response; an interrupted maintainer script can leave services and files between states.

Alternatives

  • If the active process is healthy, monitor journalctl -u apt-daily-upgrade.service -f from a second session and let it finish.

Stop conditions

  • Never delete /var/lib/dpkg/lock or lock-frontend while investigating ownership.
03

command

Check bytes, inodes, mounts, and kernel storage errors

read-only

Package unpacking and configuration require free bytes, free inodes, and writable filesystems. Inspect /, /var, /boot, and /tmp along with mount flags and recent kernel errors before asking dpkg to resume writes.

Why this step matters

A full or read-only filesystem makes package repair commands fail repeatedly and can create additional partial writes. Storage health must be restored before dpkg configuration resumes.

What to understand

A rounded 100% display may still leave a small reserve, but dpkg archives, temporary files, initramfs generation, and logs can require substantial working space.

Free bytes do not help when inodes are exhausted. Inspect both reports and the filesystem that actually backs each package path.

Kernel I/O or filesystem errors require storage recovery, not an APT workaround. Preserve evidence and avoid write-heavy retries.

System changes

  • None. The commands read filesystem capacity, mount configuration, and kernel logs.

Syntax explained

df -hT
Shows filesystem type and human-readable byte capacity for relevant paths.
df -i
Shows inode allocation independently from byte capacity.
findmnt -no
Prints exact backing devices and mount options, including ro or rw.
Command
df -hT / /var /boot /tmp 2>/dev/null
df -i / /var /boot /tmp 2>/dev/null
findmnt -no TARGET,SOURCE,FSTYPE,OPTIONS / /var /boot 2>/dev/null
journalctl -k --since '-2 hours' --no-pager | grep -Ei 'I/O error|read-only|filesystem error|ext4-fs error|xfs.*error|btrfs.*error' | tail -40 || true
Example output / evidence
Filesystem     Type  Size  Used Avail Use% Mounted on
/dev/vda2      ext4   40G   39G  180M 100% /
Filesystem     Inodes IUsed IFree IUse% Mounted on
/dev/vda2     2621440 920K  1.7M   36% /
/ /dev/vda2 ext4 rw,relatime

Checkpoint: Confirm package paths are writable with working space

test -w /var/lib/dpkg && test -w /var/cache/apt && echo package-paths-writable

Continue whenpackage-paths-writable is printed and capacity reports show enough headroom for the transaction.

Stop whenStop on read-only mounts, I/O errors, zero free inodes, or insufficient /boot space for a kernel transaction.

If this step fails

No space left on device appears before the dpkg error

Likely causeA relevant filesystem has exhausted bytes or inodes.

Safe checks
  • df -hT / /var /boot
  • df -i / /var /boot

ResolutionFree space through the normal retention process, verify filesystem health, and then return to dpkg audit. Do not delete package database files.

Alternatives

  • Expand the filesystem or move approved cache data when ordinary retention cleanup cannot provide safe working space.

Stop conditions

  • Do not run dpkg --configure -a until filesystems are healthy and writable.
04

command

Audit incomplete packages and dependency state

read-only

Use dpkg's audit action and package status abbreviations to identify unpacked, half-configured, triggers-pending, or reinstall-required records. Then ask APT to check dependencies without applying changes.

Why this step matters

The package database records the exact interrupted stage. Auditing before repair prevents an operator from assuming the named package is merely missing or that every dependency should be reinstalled.

What to understand

The first status character is desired action, the second is current state, and the third records an error flag. ii means installed and configured without an error flag.

iU means files were unpacked but configuration has not completed. iF or half-configured states require the maintainer-script cause to be addressed.

apt-get check diagnoses broken dependencies without installing or removing packages.

System changes

  • None. dpkg and APT read their databases and dependency graph.

Syntax explained

dpkg --audit
Finds partially installed packages and missing, obsolete, or inconsistent control data.
db:Status-Abbrev
Produces the compact desired, current, and error state used to find non-ii records.
apt-get check
Updates no package state; it checks dependency consistency.
Command
sudo dpkg --audit
dpkg-query -W -f='${binary:Package}\t${db:Status-Abbrev}\t${Version}\n' | awk '$2 !~ /^ii / {print}' | head -80
sudo apt-get check
Example output / evidence
The following packages have been unpacked but not yet configured.
They must be configured using dpkg --configure or the configure menu option in dselect for them to work:
 example-daemon       Example background service
example-daemon	iU 	2.4.1-1ubuntu1
Reading package lists... Done
Building dependency tree... Done

Checkpoint: Reduce the incident to a bounded package set

sudo dpkg --audit

Continue whenThe audit names the package or packages that need configuration or reinstall.

Stop whenStop if dpkg reports database or control-file corruption rather than ordinary incomplete configuration.

Security notes

  • Treat unexpected third-party packages as a supply-chain incident until their source and signature are verified.

Alternatives

  • Use dpkg-query -s '{{packageName}}' for one package when fleet-wide output is too large.

Stop conditions

  • Do not overwrite /var/lib/dpkg/status or restore an old copy without a system-recovery plan.
05

command

Simulate APT's dependency repair plan

read-only

After the first package cause and host health are understood, ask APT to calculate a fix-broken transaction in simulation mode. Review every install, upgrade, downgrade, and removal. A simulation is a decision aid, not permission to accept an unsafe plan.

Why this step matters

The fix-broken action can install or remove packages to satisfy dependencies. Simulation exposes those consequences before privileged changes and verifies candidate versions and repositories.

What to understand

A repair that removes essential, boot, remote-access, database, or application packages is not a routine fix and needs explicit review.

Candidate versions should come from the expected Ubuntu release or an approved pinned repository.

If the plan is empty but dpkg audit still reports a package, its maintainer script or configuration is the likely blocker rather than dependencies.

System changes

  • No packages are changed because apt-get runs with --simulate.

Syntax explained

--simulate
Calculates and prints the transaction without acquiring package write locks or changing packages.
--fix-broken
Lets APT propose dependency corrections for the existing incomplete state.
policy
Shows installed and candidate versions plus repository priority.
Command
Fill variables0/1 ready

Values stay on this page and are never sent or saved.

sudo apt-get --simulate --fix-broken install
apt-cache policy '{{packageName}}'
apt-cache show '{{packageName}}' 2>/dev/null | sed -n '1,30p'
Example output / evidence
Correcting dependencies... Done
The following additional packages will be installed:
 example-library
The following packages will be upgraded:
 example-daemon example-library
2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Inst example-library (2.4.1-1ubuntu1 Ubuntu:24.04/noble-updates [amd64])

Checkpoint: Approve a bounded repair transaction

sudo apt-get --simulate --fix-broken install

Continue whenThe plan contains only expected packages and no unexplained removals or repository changes.

Stop whenStop if the plan removes essential packages, crosses releases, downgrades unexpectedly, or uses an unapproved third-party source.

Alternatives

  • Repair the package's configuration or repository source first when simulation cannot form a safe plan.

Stop conditions

  • Do not run the non-simulated command until the plan and first error have both been reviewed.
06

command

Complete pending package configuration

caution

Run dpkg configuration only after locks, storage, filesystem health, and the first maintainer-script failure are resolved. Keep the full output. The command processes every unpacked package awaiting configuration, so it can start or restart services and regenerate boot artifacts.

Why this step matters

dpkg --configure --pending resumes the exact configuration stage recorded in its database without inventing a new package transaction. Captured output proves which script succeeded or failed.

What to understand

Package post-installation scripts can modify configuration, create users, regenerate caches, or restart services. Run inside a declared maintenance window.

tee preserves evidence while the terminal remains visible. PIPESTATUS records dpkg's exit code rather than tee's exit code.

If the same package fails again, stop at its first error and fix that package-specific cause instead of looping.

System changes

  • Configures all unpacked pending packages, runs their maintainer scripts and triggers, and may restart affected services or regenerate initramfs data.

Syntax explained

--configure
Runs package configuration scripts for already unpacked packages.
--pending
Selects every package whose database state requires configuration.
tee
Writes the complete transaction output to the chosen evidence file and the terminal.
Command
Fill variables0/1 ready

Values stay on this page and are never sent or saved.

sudo dpkg --configure --pending 2>&1 | tee '{{evidenceFile}}'
printf 'dpkg_exit=%s\n' "${PIPESTATUS[0]}"
Example output / evidence
Setting up example-library (2.4.1-1ubuntu1) ...
Setting up example-daemon (2.4.1-1ubuntu1) ...
Processing triggers for man-db (2.12.0-4build2) ...
dpkg_exit=0

Checkpoint: Confirm pending configuration completed

sudo dpkg --audit

Continue whenNo package remains unpacked, half-configured, triggers-pending, or reinstall-required.

Stop whenStop at the first repeated maintainer-script error; do not repeatedly invoke --configure.

If this step fails

installed package post-installation script subprocess returned error exit status 1

Likely causeThe package's postinst script encountered an application-specific configuration, service, permission, or dependency failure.

Safe checks
  • dpkg-query -s '{{packageName}}'
  • sudo journalctl -u '{{serviceName}}' -n 80 --no-pager

ResolutionDiagnose the package or service cause, restore valid configuration, and rerun only after its own validation command succeeds.

Security notes

  • Store the evidence file with restricted permissions if package scripts print hostnames, paths, or configuration values.

Alternatives

  • Use sudo dpkg --configure '{{packageName}}' for a targeted retry after the dependent package order is understood.

Stop conditions

  • Stop on boot-critical package failures, database corruption, repeated script failure, or an unexpected service restart.
07

command

Apply the reviewed fix-broken transaction

caution

If the simulation showed a safe dependency correction, run the same APT action without --simulate and review the final summary before confirming. This step may download, unpack, configure, upgrade, or remove packages exactly as shown in the approved plan.

Why this step matters

APT can obtain and order missing dependencies that dpkg alone cannot resolve. Applying only the previously simulated plan keeps the recovery bounded and reviewable.

What to understand

Read the interactive summary again because repository metadata or package state may have changed since simulation.

APT layers dependency resolution and downloads above dpkg; package configuration still runs maintainer scripts.

The follow-up check and audit distinguish successful dependency repair from a transaction that merely returned control to the shell.

System changes

  • Installs, upgrades, configures, or removes only the packages shown in the reviewed fix-broken plan and updates APT/dpkg databases.

Syntax explained

--fix-broken
Attempts to correct the existing dependency graph using available package candidates.
install
Allows APT to apply the calculated dependency correction transaction.
apt-get check
Verifies dependency consistency after the transaction.
Command
sudo apt-get --fix-broken install
sudo apt-get check
sudo dpkg --audit
Example output / evidence
Correcting dependencies... Done
Setting up example-library (2.4.1-1ubuntu1) ...
Setting up example-daemon (2.4.1-1ubuntu1) ...
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Reading package lists... Done
Building dependency tree... Done

Checkpoint: Confirm dependency and package databases agree

sudo apt-get check; sudo dpkg --audit

Continue whenBoth commands complete without dependency or incomplete-package output.

Stop whenAbort at the confirmation prompt if the live plan differs materially from the simulation.

Security notes

  • Do not add --allow-unauthenticated, force-conflicts, or unaudited repository changes to make the transaction proceed.

Alternatives

  • Use a targeted reinstall or reviewed package removal when the dependency plan remains unsafe.

Stop conditions

  • Stop if APT proposes removing SSH, init, kernel, libc, database, storage, or other essential workload packages unexpectedly.
08

decision

Reinstall or roll back one package only when evidence requires it

When dependency state is sound but one package remains damaged, choose a targeted action. Reinstall restores packaged files while preserving conffile rules. Removal is a rollback only when dependents, service ownership, data paths, and boot impact have been reviewed. Never purge by default.

Why this step matters

Targeted recovery limits the blast radius and preserves a clear audit trail. Broad removal or purge can erase configuration and cascade through dependent services.

What to understand

Run dpkg --verify and dpkg-query --show before choosing reinstall. Modified conffiles are not automatically replaced by a normal reinstall.

Simulate both reinstall and removal paths. Choose removal only when the package is optional or an approved rollback restores the previous service.

For third-party packages, verify repository origin, signing configuration, and candidate version before downloading replacement files.

System changes

  • The chosen follow-up may reinstall package-owned files or remove one reviewed package; no action is embedded in this decision step.

Syntax explained

--reinstall
Forces APT to unpack the selected package version again while following conffile policy.
--simulate remove
Shows dependent removals before a rollback is applied.
dpkg --verify
Reports changed package-managed files where verification metadata is available.
Example output / evidence
Decision: reinstall example-daemon from noble-updates; keep /etc/example-daemon/config.yml; no dependent package removals in simulation.

Checkpoint: Document the exact targeted action

Continue whenThe incident record names the package, candidate version, source, conffile decision, service effect, and simulated dependency result.

Stop whenStop if the package is essential, provides the active kernel or init system, or owns unbacked application data.

If this step fails

Package is in a very bad inconsistent state; you should reinstall it before attempting removal

Likely causedpkg lacks usable files or metadata needed to complete ordinary configuration or removal.

Safe checks
  • dpkg-query -s '{{packageName}}'
  • apt-cache policy '{{packageName}}'
  • sudo apt-get --simulate install --reinstall '{{packageName}}'

ResolutionReinstall the exact approved candidate through APT, then rerun audit. Escalate if the package database or repository cannot supply it.

Security notes

  • Back up application data and configuration separately; a package reinstall is not an application-data backup.

Alternatives

  • Restore a host snapshot or rebuild from a known image when package state cannot be recovered with bounded, verified actions.

Stop conditions

  • Do not purge a package until its conffiles, data, dependents, and rollback owner are documented.
09

verification

Verify package state, services, boot artifacts, and future updates

read-only

Finish with database checks, the recovered package record, service health, and a fresh simulation of ordinary package changes. Confirm any kernel or initramfs transaction left boot artifacts present before leaving the maintenance window.

Why this step matters

A zero exit from one repair command is not sufficient. Package databases, workload health, candidate update behavior, and boot artifacts are separate success signals.

What to understand

No dpkg audit output and a successful apt-get check prove database consistency, not application correctness.

Service status and the application's own health check prove whether package configuration produced a usable workload.

A simulated upgrade catches held or unresolved packages that could break the next routine maintenance cycle.

System changes

  • None. The commands read package, service, upgrade-plan, and boot-file state.

Syntax explained

db:Status-Abbrev
Confirms the recovered package reached the installed-and-configured ii state.
systemctl status
Shows service state and recent failure context without changing the unit.
--simulate upgrade
Checks the next ordinary update plan without modifying packages.
Command
Fill variables0/2 ready

Values stay on this page and are never sent or saved.

sudo dpkg --audit
sudo apt-get check
dpkg-query -W -f='${binary:Package}\t${db:Status-Abbrev}\t${Version}\n' '{{packageName}}' 2>/dev/null || true
if test -n '{{serviceName}}'; then systemctl --no-pager --full status '{{serviceName}}'; fi
sudo apt-get --simulate upgrade | tail -n 30
ls -lh /boot/vmlinuz-* /boot/initrd.img-* 2>/dev/null | tail -n 12
Example output / evidence
example-daemon	ii 	2.4.1-1ubuntu1
● example-daemon.service - Example background service
     Active: active (running) since Sun 2026-08-23 17:10:03 UTC; 2min ago
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Checkpoint: Close only with clean package and workload evidence

sudo dpkg --audit; sudo apt-get check

Continue whenBoth commands complete with no incomplete package or dependency error.

Stop whenKeep the incident open if the service is failed, boot files are missing, or the next upgrade simulation remains broken.

Alternatives

  • Use application-specific smoke tests and monitoring before returning traffic to the repaired service.

Stop conditions

  • Do not reboot after a kernel or initramfs failure until /boot contents and the bootloader plan are independently verified.

Finish line

Verification checklist

Confirm dpkg has no incomplete package recordssudo dpkg --auditThe command prints no package requiring configuration, reinstall, or control-data repair.
Confirm APT dependency state is consistentsudo apt-get checkAPT reads package lists and dependency information without reporting unmet dependencies.
Confirm the recovered package is installed or intentionally absentdpkg-query -W -f='${binary:Package} ${db:Status-Abbrev} ${Version}\n' '{{packageName}}' 2>/dev/null || echo intentionally-absentThe package reports ii and a version, or the approved rollback record says intentionally-absent.

Recovery guidance

Common problems and safe checks

E: Could not get lock /var/lib/dpkg/lock-frontend

Likely causeAnother package process or systemd update service owns the database.

Safe checks
  • ps -eo pid,lstart,stat,cmd | grep -E '[a]pt|[d]pkg|unattended'
  • sudo fuser -v /var/lib/dpkg/lock-frontend

ResolutionWait for a healthy transaction or stop the owning service through its documented controller after preserving logs. Do not remove the lock file.

dpkg was interrupted, you must manually run 'sudo dpkg --configure -a'

Likely causeA prior transaction unpacked packages but did not complete configuration.

Safe checks
  • sudo dpkg --audit
  • sudo apt-get check

ResolutionFirst verify no active owner, enough writable storage, and the original failure cause; then run the bounded pending-configuration step and capture output.

dependency problems - leaving unconfigured

Likely causeThe package depends on another package that is absent, incompatible, or itself failed configuration.

Safe checks
  • sudo apt-get check
  • sudo apt-get --simulate --fix-broken install

ResolutionRepair the first failed dependency or apply only the reviewed simulated fix-broken plan.

No space left on device followed by Sub-process /usr/bin/dpkg returned an error code (1)

Likely causeA filesystem needed by archives, unpacking, logs, /boot, or temporary files exhausted bytes or inodes.

Safe checks
  • df -hT / /var /boot /tmp
  • df -i / /var /boot /tmp

ResolutionRestore safe headroom through approved cleanup or expansion, check filesystem health, then rerun dpkg audit before configuration.

Package configuration fails because a service cannot start

Likely causeThe package postinst script requires valid application configuration, permissions, ports, secrets, or external services.

Safe checks
  • sudo journalctl -u '{{serviceName}}' -n 100 --no-pager
  • systemctl cat '{{serviceName}}'

ResolutionFix the service-specific cause and run its native configuration validation before retrying the package configuration.

Package is in a very bad inconsistent state

Likely causeRequired package files or metadata are missing or damaged.

Safe checks
  • dpkg-query -s '{{packageName}}'
  • apt-cache policy '{{packageName}}'
  • sudo apt-get --simulate install --reinstall '{{packageName}}'

ResolutionReinstall the exact trusted candidate through APT if the simulated plan is safe; otherwise restore or rebuild the host through the system recovery process.

After the procedure

Alternatives and next steps

Consider these alternatives

  • Restore a known-good host or image snapshot when the package database, root filesystem, or boot chain is damaged beyond a bounded package repair.
  • Rebuild an immutable server from its approved image and restore application data when local drift makes package ownership uncertain.
  • Use an Ubuntu snapshot repository or pinned approved mirror to reproduce the exact candidate set when ordinary repository state has advanced.
  • Escalate package-specific postinst failures to the service owner when valid application configuration or external dependencies are required before configuration can complete.

Operate it safely

  • Attach the first failing log excerpt, simulation, applied transaction, package versions, service checks, and final audit to the incident or maintenance record.
  • Fix automation that discarded apt output, ran package tools concurrently, lacked disk headroom checks, or retried configuration without preserving the first error.
  • Monitor the next scheduled apt update and upgrade cycle, then confirm package locks are released and no new half-configured state appears.
  • Review third-party repositories, pinned candidates, held packages, and obsolete packages so the same dependency conflict does not recur.
  • Add capacity alerts for /var and /boot plus a preflight that runs dpkg --audit and apt-get check before fleet maintenance.

Reference

Frequently asked questions

What does Sub-process /usr/bin/dpkg returned an error code (1) mean?

It means dpkg failed one or more operations. The line is a summary, not a root cause. Read earlier output to find the first package, script, dependency, filesystem, lock, or repository error.

Should I delete /var/lib/dpkg/lock or lock-frontend?

No. A live process holds a kernel lock independently from the pathname. Deleting the file can allow concurrent writers and package database damage. Identify the owner and wait or stop it safely.

Should I immediately run dpkg --configure -a?

Only after confirming no active package process, healthy writable filesystems, enough bytes and inodes, and understanding the first failure. Otherwise the same script may fail again or package state may worsen.

What does apt-get --fix-broken install do?

It asks APT to calculate a transaction that restores dependency consistency. It may install, upgrade, or remove packages, so simulate it first and reject unexpected removals or sources.

Why does the same package fail every time?

Its maintainer script is probably encountering an unresolved service configuration, permission, storage, or dependency problem. Stop retrying and diagnose the first package-specific error and journal entry.

Is reinstalling the package safe?

A targeted reinstall can restore package-owned files, but it still runs scripts and follows conffile rules. Simulate it, back up application data, verify candidate origin, and understand service effects.

When should I restore or rebuild instead of repairing?

Use broader recovery when the package database is corrupt or missing, storage has I/O errors, boot-critical packages are broken, repository ownership is unknown, or safe simulations cannot form a bounded plan.

How do I prove the recovery is complete?

dpkg --audit prints nothing, apt-get check succeeds, the package has the intended state and version, affected services pass health checks, boot artifacts are valid, and a simulated upgrade is coherent.

How often should this guide be reviewed?

Review it within 180 days and whenever supported Ubuntu releases, apt or dpkg behavior, systemd update timers, repository policy, or fleet recovery procedures change.

Recovery

Rollback

Rollback depends on the first failing package and the transaction stage. Preserve the apt term log, dpkg status database, conffile decisions, and simulated removal plan before changing state. Prefer a targeted reinstall or reviewed removal; never delete the dpkg database or lock files as a repair.

  1. Copy /var/log/apt/term.log, /var/log/apt/history.log, and the relevant /var/log/dpkg.log lines to the incident record before retrying configuration.
  2. If a newly introduced package is the cause, simulate its removal with sudo apt-get --simulate remove '{{packageName}}' and review every dependent package before applying it.
  3. If package files are damaged but configuration is valid, simulate and then run sudo apt-get install --reinstall '{{packageName}}' from the approved repository.
  4. If a maintainer script changed service configuration, restore the documented application backup and package conffile choice, then re-run only the targeted configuration and health check.
  5. For boot-critical, kernel, initramfs, libc, dpkg, or apt failures, stop general remediation and use console recovery with an approved system backup or snapshot.

Evidence

Sources and review

Verified 2026-08-23Review due 2027-02-19
Ubuntu Server documentation — Install and manage packagesofficialUbuntu manpage — dpkg package managerofficialUbuntu manpage — apt-get package handling utilityofficialDebian manpage — dpkg audit and package statesofficial