apt: Could not get lock /var/lib/dpkg/lock-frontend
The lock names its holder, so read it instead of deleting the file. Wait, time out, or stop unattended-upgrades for the duration.

Introduction & Quick Summary
Symptom. In the middle of a provisioning script, a Dockerfile or an Ansible play:
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2471 (unattended-upgr)
N: Be aware that removing the lock file is not a solution and may break your system.
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?On a freshly booted cloud VM it happens seconds after cloud-init started, and on an existing server it happens at the same hour every day. Meanwhile the packages you meant to install are missing and the script exits.
Cause. dpkg serialises every change to the package database with a lock, and apt takes a frontend lock before it calls dpkg. Another process already holds it: unattended-upgrades applying security updates, the apt-daily timers, cloud-init installing packages at first boot, another terminal's apt install, or a previous apt that was killed and left dpkg half-configured.
Fix. Wait for the holder, or take the lock properly with a timeout instead of racing it.
# who holds it, and is it still alive
sudo fuser -v /var/lib/dpkg/lock-frontend
ps -o pid,etime,cmd -p "$(sudo fuser /var/lib/dpkg/lock-frontend 2>/dev/null)"
# wait up to two minutes instead of failing
sudo apt-get -o DPkg::Lock::Timeout=120 install -y nginx# after a killed apt: finish the interrupted configuration
sudo dpkg --configure -a
sudo apt-get -f installCore Mechanics, Signatures & Reproducible Setup
There are four locks and they mean different things. /var/lib/dpkg/lock-frontend is taken by apt to serialise whole operations; /var/lib/dpkg/lock guards the database itself and is taken by dpkg; /var/lib/apt/lists/lock guards the package list cache during apt-get update; /var/cache/apt/archives/lock guards .deb downloads. The message names whichever one apt could not take, so the first step is reading it rather than deleting a file.
Reproduce the interaction without touching a production host:
# hold the frontend lock for 60 seconds, as unattended-upgrades would
sudo sh -c 'exec 9>/var/lib/dpkg/lock-frontend; flock -n 9 || exit 1; sleep 60' &
sleep 1
sudo apt-get install -y curl # fails with the message above
sudo fuser -v /var/lib/dpkg/lock-frontendThat is the whole diagnosis: flock shows the pid, fuser names it, and the correct action is to wait for it or stop the service that owns it deliberately.
The supported ways to deal with a busy lock, in order of preference:
# 1. a timeout, in apt, yum-style
sudo apt-get -o DPkg::Lock::Timeout=300 upgrade
# 2. stop the update runner for the duration of your change
sudo systemctl stop unattended-upgrades apt-daily.timer apt-daily-upgrade.timer
sudo systemctl start unattended-upgrades # put it back afterwards
# 3. schedule your work outside the daily window
systemctl list-timers 'apt-*' 'unattended*'Key Comparison Table
| Lock file | Held by | Blocks |
|---|---|---|
/var/lib/dpkg/lock-frontend | apt, apt-get, aptitude | every install, upgrade and remove |
/var/lib/dpkg/lock | dpkg itself | direct dpkg -i and recovery |
/var/lib/apt/lists/lock | apt-get update | refreshing package lists |
/var/cache/apt/archives/lock | download phase | fetching and cleaning .deb files |
| Situation | Right action | Wrong action |
|---|---|---|
unattended-upgr is running | wait, or stop the service | delete the lock file |
cloud-init is installing | cloud-init status --wait first | run apt in parallel |
apt killed mid-install | dpkg --configure -a | install again immediately |
| Laptop suspend left a stale process | check ps, then kill that pid | rm /var/lib/dpkg/lock* |
| Ansible or CI concurrent tasks | serialise the task, use lock_timeout | retry in a tight loop |
| Docker build | build as root, one apt layer | mount the host's dpkg database |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. cloud-init at first boot
On a fresh VM, cloud-init installs packages during boot and the lock is legitimately held for thirty seconds to a few minutes. Waiting is the correct fix, and it makes a provisioning script deterministic instead of lucky:
cloud-init status --wait
# or, when cloud-init is not the holder, still wait for the lock politely
while sudo fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do sleep 2; doneThe loop needs a timeout in production; an unattended apt waiting forever is its own outage. timeout 300 bash -c '...' around it, then fail loudly.
2. A stale lock after a killed process
A lock is a file descriptor, not a file, so a dead process releases it. A lock that looks stuck usually means a live process is genuinely waiting on something, or the file is held by a process inside a container sharing the same filesystem:
sudo lsof /var/lib/dpkg/lock-frontend
sudo lsof /var/lib/dpkg/lockIf lsof shows nothing and dpkg still refuses, the database is likely half-configured rather than locked; dpkg --configure -a is the recovery path, not file deletion. Removing the lock file while another dpkg is mid-write can leave the package database inconsistent in a way that survives reboots.
3. Docker builds and cached apt layers
Two separate failures appear in Dockerfiles. The first is the lock, from a base image whose entrypoint starts an update service. The second is E: Unable to locate package, because apt-get update lives in a cached layer from a previous run while the install command runs in a new one:
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl \
&& rm -rf /var/lib/apt/lists/*Always combine update and install in one RUN, and drop the lists afterwards. In CI, --no-install-recommends and the cleanup cut the layer size and the number of files, which matters if the builder disk is small.
4. Ansible, Terraform provisioners and parallel hosts
Concurrent tasks on the same host are the second most common cause after unattended-upgrades. Ansible has a first-class answer; use it rather than a retry loop:
- name: Install packages
ansible.builtin.apt:
name: [nginx, curl]
state: present
lock_timeout: 180
register: apt_result
until: apt_result is succeeded
retries: 3
delay: 10For shell tasks, apt-get -o DPkg::Lock::Timeout=180 is equivalent and works in any provisioner.
5. Disabling automatic upgrades is a decision, not a fix
Stopping unattended-upgrades permanently makes the lock go away and leaves the host without security updates. If you need a maintenance window, mask the timers, do the work, then unmask them, and prefer apt-daily.timer overrides with RandomizedDelaySec so a fleet does not all update at the same minute:
sudo systemctl edit apt-daily.timer
# [Timer]
# RandomizedDelaySec=2h
# Persistent=true6. Verifying that a package operation actually finished
A script that ignores the exit code can leave dpkg interrupted, and the next failure appears hours later as a missing binary. Check the two states explicitly:
sudo dpkg --audit
dpkg -l | awk '/^..U|^..H/ {print}' # unknown or half-installed packagesAn empty --audit and no U/H rows mean the database is consistent. Anything else should be repaired before the next operation, and repairing is always --configure -a plus -f install, never deleting lock files.
Common Compilation/Runtime Mistakes & Version Gotchas
- Deleting
/var/lib/dpkg/lock*. It does not release a held descriptor and it can corrupt the database. - Retrying in a shell loop with no delay. It burns CPU and can starve the process that holds the lock.
- Stopping
unattended-upgradespermanently. The lock disappears and so do security patches. - Putting
apt-get updatein a separate Docker layer. The install then runs against stale lists. - Splitting
updateandinstallacrossRUNstatements in CI caches. Same failure, different layer. - Ignoring
dpkg --auditafter a failure. The half-configured state reappears as a missing binary later. - Running two provisioning tools against one host. Pick one owner for package state.
Work out when the unattended window actually starts by reading the timer expressions with the cron schedule tool, and keep the lock files' permissions in view with the chmod calculator when a container runs as a non-root user.
Reference: dpkg manual and Ubuntu Server package management.
Official references
primary documentationThe Linux documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Linux guides
All Linux guidesnginx 502 Bad Gateway: upstream connection refused
The log line names the address and errno, which is the diagnosis. Fix the host, the start-up order, the buffers, or the timeout that actually fired.
Linux: Too many open files (EMFILE) and ulimit
EMFILE is a per-process descriptor limit, ENFILE is the kernel's. Read the limit from /proc, raise it in the right layer, and find the leak that made it matter.
systemd status=203/EXEC and 217/USER: Exec and Permission Failures
203 is a failed execve, 217 is a user systemd could not resolve. Both happen before your program runs, and the check that finds each takes one command.
systemd Timers vs Cron: Missing PATH, Overlapping Runs, Time Drift
Cron runs a bare shell with no profile and no locking, and systemd reads the system time zone. The environment, single-instance and schedule fixes for both.
More in Linux
All Linux guidesThe guides filed next to this one in Linux, in library order.