Containerize a PyPI package using rockcraft

By the end of this tutorial you will be able to run pyfiglet via docker:

$ docker run --rm -it pyfiglet:0.7.6 exec pyfiglet hello
 _          _ _       
| |__   ___| | | ___  
| '_ \ / _ \ | |/ _ \ 
| | | |  __/ | | (_) |
|_| |_|\___|_|_|\___/ 

Prerequisites

rockcraft, docker, skopeo and lxd are installed (there is a multipass docker blueprint to help with that).

rockcraft.yaml

With rockcraft, we build images from a rockcraft.yaml file rather than a Dockerfile.

To create a new rock project,

mkdir pyfiglet-rock && cd pyfiglet-rock
rockcraft init

Next, update the file to look like this:

name: pyfiglet
base: ubuntu:22.04
version: '0.7.6'  # Note: should match `pyfiglet` below
summary: A rock for pyfiglet
description: A rock for pyfiglet
license: Apache-2.0
platforms:
  amd64:

parts:
  pyfiglet:
    plugin: python
    source: .
    python-packages:
      - pyfiglet==0.7.6  # Note: should match `version` above
    stage-packages:
      - python3-venv

Pack and run

Now, build the rock:

rockcraft clean && rockcraft pack -v

Next, import the rock into docker:

skopeo --insecure-policy copy oci-archive:pyfiglet_0.7.6_amd64.rock docker-daemon:pyfiglet:0.7.6

The image is now ready to be run. The default entrypoint is pebble, and we use pebble exec to run one-shot commands:

$ docker run --rm -it pyfiglet:0.7.6 exec pyfiglet it works!
 _ _                        _        _ 
(_) |_  __      _____  _ __| | _____| |
| | __| \ \ /\ / / _ \| '__| |/ / __| |
| | |_   \ V  V / (_) | |  |   <\__ \_|
|_|\__|   \_/\_/ \___/|_|  |_|\_\___(_)

To be able to poke around the container, you could add bash to stage-packages:

    stage-packages:
+     - bash

After repeating rockcraft pack and skopeo copy you should be able to override the entrypoint:

$ docker run --rm -it --entrypoint bash pyfiglet:0.7.6      
root@14d1812a2681:/# pyfiglet hi
 _     _ 
| |__ (_)
| '_ \| |
| | | | |
|_| |_|_|         
5 Likes