How to make a portable Alpine linux chroot

This is a guide to create a tar.gz archive of an Alpine linux chroot that can be deployed on systems without an active internet connection.

Why

When working with legacy or corporate systems we can have the following problems:

What

A chroot is a directory that we can change to a new root tree for applications that live inside it. This new root could be of a completely different linux distribution and anything inside of it cannot peak out (At a filesystem level).

Because of this, the chroot should only have was is required, as if multiple chroot’s are needed storage is duplicated. Special files also need to be added as required, this includes /dev, /sys and /proc.

In short a chroot can be thought as filesystem isolation and remapping. It allows us to get the applications to where we need them without making major changes to the host’s system.

Instructions

Host with internet

Setup base chroot

  1. Download a minirootfs of Alpine linux
    $ wget http://dl-cdn.alpinelinux.org/alpine/v3.12/releases/x86_64/alpine-minirootfs-3.12.0-x86_64.tar.gz
    
  2. Create a directory and extract the archive into it
    $ mkdir alpine
    $ tar zxf alpine-minirootfs-*.tar.gz -C ./alpine
    
  3. Add /dev/* devices
    # mount /dev/ ./alpine/dev/ --bind
    # mount -o remount,ro,bind ./alpine/dev
    
  4. Add the host’s resolve file
    $ cp -L /etc/resolv.conf ./alpine/etc/
    
  5. Create the /root directory
    $ mkdir -p /alpine/root
    

Install packages and other files

Creating the new archive

  1. Unmount /dev

    # umount ./alpine/dev
    

  2. Remove resolve file

    $ rm -f /etc/resolve.conf
    
  3. Create archive

    $ tar zcf alpine-with-packages.tar.gz -C ./alpine
    

Host without internet

Setup chroot

  1. Create chroot directory and extract archive

    $ mkdir -p ./alpine
    $ tar zxf alpine-with-packages.tar.gz -C ./alpine
    
  2. Configure /dev/*

    # mknod -m 666 ./alpine/dev/full c 1 7
    # mknod -m 666 ./alpine/dev/ptmx c 5 2
    # mknod -m 644 ./alpine/dev/random c 1 8
    # mknod -m 644 ./alpine/dev/urandom c 1 9
    # mknod -m 666 ./alpine/dev/zero c 1 5
    # mknod -m 666 ./alpine/dev/tty c 5 0
    

    This can depend on what your applications needs but this is a good minimum, more information can be found here.

  3. Add the host’s resolve file

    $ cp -L /etc/resolv.conf ./alpine/etc/
    

Using the chroot

This is the same as when you configured the chroot.

All applications can be launched directly with

$ chroot ./alpine /path/to/bin

or via its service

$ chroot ./alpine rc-service something start

Remember

All paths are relative to the chroot.

# File on host
./alpine/srv/file

# File in chroot
/srv/file

References