How to install packages on alpine-based containers

2 min read | by Jordi Prats

Whether you are running containers on Kubernetes or in docker you might need to install packages on the running containers. You will notice that most of them are based on Alpine Linux because of its small size.

Alpine Linux is a distribution based on musl and BusyBox with its own package-management system, apk-tools.

For installing packages we will have to use the apk command. But since container's size is always a concern you most likely will find that it's cache has been purged:

# apk search apache
WARNING: Ignoring https://dl-cdn.alpinelinux.org/alpine/v3.13/main: No such file or directory
WARNING: Ignoring https://dl-cdn.alpinelinux.org/alpine/v3.13/community: No such file or directory

Using apk update we will be able to update it's cache to be able to search for packages:

# apk update
fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/community/x86_64/APKINDEX.tar.gz
v3.13.2-58-ge3f19cedc6 [https://dl-cdn.alpinelinux.org/alpine/v3.13/main]
v3.13.2-57-gb49ace1568 [https://dl-cdn.alpinelinux.org/alpine/v3.13/community]
OK: 13877 distinct packages available

Once the cache has been update we can search it using apk search, for example:

# apk search libmagic
file-dev-5.39-r0
libmagic-5.39-r0

To install a package we can use apk add:

# apk add libmagic
(1/1) Installing libmagic (5.39-r0)
OK: 155 MiB in 29 packages

If you want to use alpine as a base image you can combine the flags --update and --no-cache so you don't have to worry about cleaning the apk cache after installing some packages:

FROM python:3.8-alpine
RUN apk add --no-cache --update gcc

Actually, the apk's --update flag is a shorthand for --update-cache since it does not collide with other options.


Posted on 19/03/2021