How to install packages on alpine-based containers

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 No such file or directory
WARNING: Ignoring 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
v3.13.2-58-ge3f19cedc6 []
v3.13.2-57-gb49ace1568 []
OK: 13877 distinct packages available

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

# apk search libmagic

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