How to Install zlib on Ubuntu

zlib is a widely used compression library that provides in-memory compression and decompression functions for data streams. It powers the gzip and PNG file formats and serves as a critical dependency for compiling software from source. Most users encounter zlib when building applications that require compression capabilities or when package build processes list it as a prerequisite.

On Ubuntu, zlib installs via the default APT repository for stable, maintained versions, or by compiling from source when you need the absolute latest features or optimizations. This guide covers both methods with concrete examples and verification steps, so you can choose the approach that fits your workflow.

Choose Your zlib Installation Method

Pick the approach that fits your workflow before diving into the commands. Repository packages integrate with Ubuntu’s automatic updates, while source builds deliver the newest code at the cost of extra maintenance.

MethodChannelStabilityBest For
APT package (zlib1g-dev)Ubuntu main repositoryFully tested with automated security updatesDevelopers who want painless system integration and predictable updates
Compile from sourceGitHub release tarballsDepends on upstream release quality and your build optionsUsers who need newer compression features or custom compiler optimizations

For most users, the APT method is recommended because it provides automatic security updates and requires minimal maintenance. Only compile from source if you specifically need features unavailable in the repository version or require custom compilation flags for specialized applications.

This guide covers Ubuntu 22.04 LTS, 24.04 LTS, and 26.04 LTS. The APT repository provides different zlib versions depending on your Ubuntu release (1.2.11 on 22.04, 1.3 on 24.04, and 1.3.1 on 26.04), but all installation commands work identically across supported LTS releases.

Method 1: Install zlib via Ubuntu’s Default Repository

The APT method installs zlib development files from Ubuntu’s official repositories. This approach ensures automatic security updates and proper integration with other system packages.

Update Ubuntu Before zlib Installation

Before installing zlib, update your package lists to ensure you install the latest available version. You can review the process in our APT maintenance guide if you need a refresher on package management.

sudo apt update

After updating the package list, apply any available upgrades to ensure a stable environment:

sudo apt upgrade

Check for Existing zlib Installation

First, verify whether zlib development files are already present on your system:

dpkg -l | grep zlib1g-dev

The dpkg -l portion lists installed packages, while the grep command filters that list for zlib1g-dev. If zlib development files are already installed, you will see output similar to this:

ii  zlib1g-dev:amd64   1:1.3.dfsg+really1.3.1-1ubuntu2   amd64   compression library - development

The ii prefix indicates the package is installed and configured correctly. The version number varies by Ubuntu release, but any output confirms zlib development files are present. If no output appears, proceed with installation.

Install zlib Development Package

Install the zlib development package, which contains header files and static libraries necessary for compiling software that uses zlib compression. The zlib1g-dev package provides everything needed to build applications from source that depend on zlib:

sudo apt install zlib1g-dev

APT resolves dependencies automatically, so any required packages install alongside zlib1g-dev.

Verify zlib Installation

Confirm the installation succeeded by checking the installed version. The pkg-config utility reports metadata for development libraries, so install it first if it is not already present:

sudo apt install pkg-config

Then run the command to display the installed zlib version:

pkg-config --modversion zlib

The output shows the zlib version number. Your version depends on your Ubuntu release:

Ubuntu 26.04 LTS:

1.3.1

On 24.04 LTS:

1.3

For 22.04 LTS:

1.2.11

Any version output confirms successful installation. The pkg-config utility reads metadata from installed development libraries, making it the standard method for verifying library availability before compilation.

If the command returns Package zlib was not found, reinstall the development files with sudo apt install --reinstall zlib1g-dev and verify pkg-config itself is on your PATH using which pkg-config.

Method 2: Install zlib via Source Compilation

Alternatively, you can compile zlib from source to access the latest version or when you need specific build configurations unavailable in the repository package. This approach requires manual maintenance: future updates require downloading and recompiling new releases rather than receiving automatic APT updates.

Install Build Dependencies

Source code compilation requires a compiler and build tools to transform human-readable code into executable binaries. Install the build-essential package, which bundles the GCC compiler, linker, and Make automation tool needed for building software on Ubuntu:

sudo apt install build-essential wget curl -y

The build-essential package includes gcc, make, and other essential development tools. The wget and curl utilities handle downloading source archives.

Download the zlib Source Code

Download the latest zlib source code from the official GitHub releases. The following commands automatically detect the latest version and download the corresponding tarball:

cd /tmp
ZLIB_VERSION=$(curl -fsSL https://api.github.com/repos/madler/zlib/releases/latest | grep -oP '"tag_name": "v\K[^"]+')
echo "Downloading zlib version: $ZLIB_VERSION"
wget -q "https://github.com/madler/zlib/archive/refs/tags/v${ZLIB_VERSION}.tar.gz" -O "zlib-${ZLIB_VERSION}.tar.gz"

The GitHub API query uses curl to retrieve the latest release tag, ensuring you always download the current stable version. A successful download displays the detected version:

Downloading zlib version: 1.3.1

If the automatic download fails due to network restrictions, visit the zlib GitHub releases page manually to download the latest .tar.gz source archive.

Extract the Source Archive

Once downloaded, extract the archive using the tar command:

tar -xzf zlib-${ZLIB_VERSION}.tar.gz
cd zlib-${ZLIB_VERSION}

The -x flag extracts, -z handles gzip compression, and -f specifies the filename. The extraction creates a directory matching the version number.

Configure the Build

Configure the zlib build with a custom installation prefix. The --prefix flag sets where zlib installs, using /usr/local/zlib to keep the custom build separate from system-managed packages:

./configure --prefix=/usr/local/zlib

The configure script analyzes your system environment and generates the Makefile needed for compilation. You will see output showing detected features and settings:

Checking for gcc...
Checking for shared library support...
Building shared library libz.so.1.3.1 with gcc.
Checking for size_t... Yes.
Checking for off64_t... Yes.
Checking for fseeko... Yes.
Checking for strerror... Yes.
Checking for unistd.h... Yes.
Checking for stdarg.h... Yes.
Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf().
Checking for vsnprintf() in stdio.h... Yes.
Checking for return value of vsnprintf()... Yes.
Checking for attribute(visibility) support... Yes.

These checks ensure zlib builds with optimal settings for your system architecture. All checks should show “Yes” for a successful configuration.

Compile the Source Code

After configuration completes, compile the zlib source code. The -j$(nproc) flag uses all available CPU cores for faster compilation:

make -j$(nproc)

Compilation typically completes in under a minute. The output shows compiler commands and should end without errors.

Run the Test Suite

Run the upstream validation suite before installing to catch issues introduced by compiler optimizations or missing dependencies:

make test

All tests should finish with an OK status:

hello world
zlib version 1.3.1 = 0x1310, compile flags = 0xa9
uncompress(): hello, hello!
gzread(): hello, hello!
gzgets() after gzseek:  hello!
inflate(): hello, hello!
large_inflate(): OK
after inflateSync(): hello, hello!
inflate with dictionary: hello, hello!
		*** zlib 64-bit test OK ***

If any test fails, reinstall the build dependencies or verify GCC is working correctly before retrying.

Install the Compiled Library

After the test suite passes, install the compiled zlib library to the configured prefix location:

sudo make install

This copies the compiled library files, headers, and pkg-config metadata to /usr/local/zlib.

Configure the Dynamic Linker

Since /usr/local/zlib is not part of Ubuntu’s default linker paths, add it to a configuration snippet so applications can find the new library:

echo "/usr/local/zlib/lib" | sudo tee /etc/ld.so.conf.d/zlib-custom.conf
sudo ldconfig

The first command creates a configuration file that registers the custom library path. The ldconfig command updates the system’s shared library cache, allowing the dynamic linker to locate your custom zlib installation when applications request compression functions at runtime. Without this step, applications may fail to find the library even though it is installed.

Verify Source Installation

After installation completes, confirm the compiled zlib installed correctly by checking the library location:

ls -la /usr/local/zlib/lib/

Successful installation produces output showing the compiled library files:

total 292
drwxr-xr-x 3 root root   4096 Jan  3 08:38 .
drwxr-xr-x 5 root root   4096 Jan  3 08:38 ..
-rw-r--r-- 1 root root 152172 Jan  3 08:38 libz.a
lrwxrwxrwx 1 root root     13 Jan  3 08:38 libz.so -> libz.so.1.3.1
lrwxrwxrwx 1 root root     13 Jan  3 08:38 libz.so.1 -> libz.so.1.3.1
-rwxr-xr-x 1 root root 129712 Jan  3 08:38 libz.so.1.3.1
drwxr-xr-x 2 root root   4096 Jan  3 08:38 pkgconfig

The output confirms both the shared library (libz.so.1.3.1) and static library (libz.a) installed successfully. The symbolic links allow applications to link against zlib using the generic name while the system loads the specific version.

Configure pkg-config for Custom Installation

When compiling other software that depends on this custom zlib build, configure pkg-config to find your installation by exporting the library path:

export PKG_CONFIG_PATH=/usr/local/zlib/lib/pkgconfig:$PKG_CONFIG_PATH

This environment variable tells pkg-config where to search for library metadata files. Without this export, build systems will find the system version instead of your custom installation.

To persist the variable for future shell sessions, add it to your shell configuration file:

echo 'export PKG_CONFIG_PATH=/usr/local/zlib/lib/pkgconfig:$PKG_CONFIG_PATH' >> ~/.bashrc
source ~/.bashrc

The source command reloads the configuration file in your current shell session, applying the change immediately. Alternatively, open a new terminal window for the changes to take effect automatically.

Verify the variable is set correctly:

echo $PKG_CONFIG_PATH

The output should include your custom zlib path first:

/usr/local/zlib/lib/pkgconfig:/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/share/pkgconfig

Your custom path appears first, ensuring build systems find your zlib installation before checking system paths.

Update Source-Compiled zlib

Unlike APT packages, source-compiled installations require manual updates when new versions release. The following script automates this process by detecting the latest version, comparing it with your current installation, and recompiling if needed.

Create the update script:

nano ~/update-zlib.sh

Add the following content:

#!/bin/bash
# zlib Source Update Script
# Updates source-compiled zlib installation to the latest version

set -e

echo "Checking for latest zlib version..."
LATEST=$(curl -fsSL https://api.github.com/repos/madler/zlib/releases/latest | grep -oP '"tag_name": "v\K[^"]+')

if [ -f /usr/local/zlib/lib/libz.so ]; then
    CURRENT=$(strings /usr/local/zlib/lib/libz.so | grep -oP '^1\.[0-9]+\.[0-9]+$' | head -1)
else
    CURRENT="not installed"
fi

echo "Current installed version: $CURRENT"
echo "Latest available version: $LATEST"
echo ""

if [ "$CURRENT" = "$LATEST" ]; then
    echo "Already running the latest version. No update needed."
    exit 0
fi

read -p "Continue with update? (y/n) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Update cancelled."
    exit 0
fi

echo "Downloading zlib ${LATEST}..."
cd /tmp
rm -rf zlib-${LATEST} zlib-${LATEST}.tar.gz
wget -q "https://github.com/madler/zlib/archive/refs/tags/v${LATEST}.tar.gz" -O "zlib-${LATEST}.tar.gz"

echo "Extracting source code..."
tar -xzf zlib-${LATEST}.tar.gz
cd zlib-${LATEST}

echo "Configuring build..."
./configure --prefix=/usr/local/zlib > /dev/null

echo "Compiling zlib (this may take a moment)..."
make -j$(nproc) > /dev/null

echo "Running tests..."
make test > /dev/null

echo "Installing zlib (requires sudo password)..."
sudo make install > /dev/null
sudo ldconfig

echo ""
echo "Update complete!"
echo "New version: $(strings /usr/local/zlib/lib/libz.so | grep -oP '^1\.[0-9]+\.[0-9]+$' | head -1)"

Save the file by pressing Ctrl+O, then Enter, then exit with Ctrl+X. Make the script executable:

chmod +x ~/update-zlib.sh

Run the script when you want to check for updates:

~/update-zlib.sh

The script shows your current version and the latest available version, asks for confirmation before proceeding, and displays progress messages throughout the update process:

Checking for latest zlib version...
Current installed version: 1.3.1
Latest available version: 1.3.1

Already running the latest version. No update needed.

Troubleshooting

Package zlib Was Not Found

If pkg-config --modversion zlib returns “Package zlib was not found,” the .pc metadata file is missing or not in the search path.

For APT installations:

sudo apt install --reinstall zlib1g-dev pkg-config
pkg-config --modversion zlib

For source installations: Verify the PKG_CONFIG_PATH includes the custom installation path:

echo $PKG_CONFIG_PATH | grep -q "/usr/local/zlib" && echo "Path configured" || echo "Path missing"

If the path is missing, add it to your shell configuration as shown in the source installation section.

Configure Script Fails with Missing Compiler

If ./configure fails with “Checking for gcc… No” or similar errors, the build tools are not installed:

sudo apt install build-essential
gcc --version

Verify GCC is available before retrying the configure step.

Applications Cannot Find Custom zlib

If applications fail to load the custom zlib library at runtime, the dynamic linker cache may need refreshing:

cat /etc/ld.so.conf.d/zlib-custom.conf
sudo ldconfig
ldconfig -p | grep libz

The first command verifies the configuration file exists and contains the correct path. The ldconfig command rebuilds the cache. The final command should show your custom library path in the output:

libz.so.1 (libc6,x86-64) => /usr/local/zlib/lib/libz.so.1
libz.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libz.so.1
libz.so (libc6,x86-64) => /usr/local/zlib/lib/libz.so

If your custom path appears, the linker is configured correctly. Applications should load from /usr/local/zlib first.

Conflicting System and Custom Installations

If you have both APT-installed and source-compiled zlib, applications may load the wrong version. Check which library an application uses:

ldd /path/to/your/application | grep libz

To force applications to use the custom version at compile time, set both PKG_CONFIG_PATH and LD_LIBRARY_PATH:

export PKG_CONFIG_PATH=/usr/local/zlib/lib/pkgconfig:$PKG_CONFIG_PATH
export LD_LIBRARY_PATH=/usr/local/zlib/lib:$LD_LIBRARY_PATH

Remove zlib

If you no longer need zlib development files or want to switch between installation methods, follow the appropriate removal steps below.

Remove APT-Installed zlib

Remove the development package and any orphaned dependencies:

sudo apt remove zlib1g-dev
sudo apt autoremove

The zlib1g runtime library remains installed because many system applications depend on it. Only the development headers and static libraries are removed. This is expected behavior.

Verify removal:

pkg-config --modversion zlib

This should return “Package zlib was not found” after removal.

Remove Source-Compiled zlib

Source-compiled zlib requires manual removal of installed files and configuration changes:

The following commands permanently delete the custom zlib installation at /usr/local/zlib. If you have applications that depend on this specific installation, they will fail to load until you reinstall zlib or reconfigure them to use the system version.

sudo rm -rf /usr/local/zlib
sudo rm -f /etc/ld.so.conf.d/zlib-custom.conf
sudo ldconfig

If you added the PKG_CONFIG_PATH export to your shell configuration, remove that line from ~/.bashrc:

nano ~/.bashrc

Find and delete the line containing export PKG_CONFIG_PATH=/usr/local/zlib, then save and reload:

source ~/.bashrc

Optionally, remove the update script if you created one:

rm -f ~/update-zlib.sh

After removal, applications will automatically use the system zlib from the APT repository if installed.

Useful Links

Explore the following resources to learn more about zlib:

  • zlib Official Website: General information and official download links for the latest stable releases.
  • zlib Manual: Complete API documentation for developers integrating zlib into applications.
  • zlib How-to Guide: Practical programming examples and implementation patterns for common compression tasks.
  • zlib GitHub Releases: Latest versions, release notes, and changelog for tracking updates.
  • zlib GitHub Wiki: Community documentation, troubleshooting tips, and contributed tutorials.

Conclusion

Both installation methods serve distinct use cases. The APT method provides automatic updates and seamless system integration suitable for most development workflows, while source compilation delivers access to the latest features when repository versions lag behind upstream releases. Source-compiled versions require manual recompilation for updates, whereas APT-managed packages update automatically through standard system maintenance. With zlib development files now available on your system, you can compile software that depends on compression functionality and build applications from source that list zlib as a prerequisite.

Leave a Comment