From 4a1973cc195fc954bff73ebf6fc0d2e5aa53d998 Mon Sep 17 00:00:00 2001 From: babic_a Date: Wed, 25 Nov 2026 14:03:34 +0100 Subject: [PATCH] SECCTRL-298: how-to for building and publishing container images Co-Authored-By: Claude Fable 5.2 --- .../03_how_to/09_containers.md | 229 ++++++++++++++++++ .../03_how_to/images/09_containers_path.svg | 126 ++++++++++ 2 files changed, 355 insertions(+) create mode 100644 docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg diff --git a/docs/3._Knowledge_Center/03_how_to/09_containers.md b/docs/3._Knowledge_Center/03_how_to/09_containers.md index aec75f4a..dcca6422 100644 --- a/docs/3._Knowledge_Center/03_how_to/09_containers.md +++ b/docs/3._Knowledge_Center/03_how_to/09_containers.md @@ -8,3 +8,232 @@ tags: --- # How-To: Use Containers + +To run your service in a container on Controls infrastructure, you package it as an image, publish the image to a registry, and a **container host** pulls it and runs it with Podman under systemd. This page is mostly about the first two steps; running the image is the short last section. + +![From the source repository to a container host: podman build turns the Containerfile and code into an image, podman tag gives it a version, podman push or Gitea Actions on a version tag publishes it to gitea.psi.ch, and the container host pulls it](images/09_containers_path.svg) + +## What is in place and what is planned + +| | Today | Planned | +|---|---|---| +| Build and registry | Podman on your machine or Gitea Actions; the Gitea registry `gitea.psi.ch` | | +| Container hosts | 12 hosts for web applications; containers run as root systemd units with `podman run` | Rootless Podman, Quadlet units, deployment through the catalogue | +| Soft IOCs | On soft IOC hosts, not in containers | Rootless Podman for soft IOCs that suit it | + +## 1. Package your application as an image + +### What goes into the image + +An image holds your code and everything it needs to run: the Python version, the packages from `requirements.txt`, system libraries. It does **not** hold passwords, tokens, host-specific settings or data. Those come from the host when the container starts (environment variables, mounted files and directories), so the same image runs unchanged on a test host and on the production host. + +One image runs one process. If your application needs a database or a cache, that is a separate container from its own image. + +A small project looks like this: + + myapp/ + Containerfile + .containerignore + requirements.txt + app.py + +Podman reads `Containerfile` or `Dockerfile`, and `.containerignore` or `.dockerignore`; use one of each. + +### The Containerfile + +A Containerfile for a Python service: + + FROM python:3.11-slim + WORKDIR /app + COPY requirements.txt . + RUN pip install --no-cache-dir -r requirements.txt + COPY app.py . + ENV PYTHONUNBUFFERED=1 + RUN useradd --create-home --uid 10001 appuser + USER appuser + EXPOSE 8000 + CMD ["python", "app.py"] + +Line by line: + +- `FROM python:3.11-slim` is the base image: Debian slim with Python 3.11. Name the Python version in the tag, never `python:latest`, so a rebuild next year gives the same Python. The `-slim` variant keeps the image small. +- `WORKDIR /app` is the directory the following lines and the program work in. +- `COPY requirements.txt .` and `RUN pip install --no-cache-dir -r requirements.txt` install the dependencies before the code is copied. Podman reuses this layer while `requirements.txt` is unchanged, so a code change rebuilds in seconds. `--no-cache-dir` keeps pip's download cache out of the image. Pin versions in `requirements.txt`. +- `COPY app.py .` copies the code. Copy only what the program needs at run time. +- `ENV PYTHONUNBUFFERED=1` makes Python write its output immediately. Without it, print output waits in a buffer and reaches the journal late or not at all when the process dies. +- `RUN useradd --create-home --uid 10001 appuser` and `USER appuser` run the program as an ordinary user with a fixed uid. A fixed uid lets you give a mounted data directory the right owner. +- `EXPOSE 8000` documents the port the program listens on; it opens nothing by itself. +- `CMD ["python", "app.py"]` starts the program. Use this list (exec) form: Python is then the main process of the container and receives the stop signal directly. The plain string form starts a shell in between, and the program is killed after the stop timeout instead of ending cleanly. + +Settings that change between hosts are read from environment variables in `app.py` (for example `os.environ["DATABASE_URL"]`), not written into the Containerfile. + +### The ignore file + +`.containerignore` keeps files out of the build. Everything not listed is sent to the build and may end up in the image through a `COPY`. From the [gfa-monitoring](https://gitea.psi.ch/controls_it/gfa_monitoring) project: + + .git + .venv + venv + __pycache__ + *.pyc + *.log + tests + .env + +`.env` is in the list because it holds secrets on a developer's machine. + +### Build and test locally + +1. Build the image. The container hosts are x86_64 machines; on a Mac with Apple Silicon Podman builds for arm64 unless you name the platform, and that image does not start on the host: + + podman build --platform linux/amd64 -t myapp:dev . + +2. Run it in the foreground; `Ctrl-C` stops it: + + podman run --rm --name myapp -p 8000:8000 myapp:dev + +3. In a second terminal, look at it while it runs: + + podman ps + podman logs -f myapp + +4. Check that it stops cleanly. `podman stop` sends the stop signal and kills the process after 10 seconds: + + time podman stop myapp + + If this takes 10 seconds, the program does not end on the stop signal: check the `CMD` form and that your program handles `SIGTERM`. + +5. Check the size in the SIZE column: + + podman image ls myapp + +Check that it worked: the application answers on `http://localhost:8000` (or prints its output), its messages appear in `podman logs`, and `podman stop` returns at once. + +## 2. Publish the image to the registry + +Controls images are published to the container registry built into Gitea, `gitea.psi.ch`. + +### Name and tags + +A published image is named after the Gitea organisation and repository it belongs to, in lower case: + + gitea.psi.ch//: + +One image gets several tags. The gfa-monitoring release workflow gives each release: + +| Tag | Example | Meaning | +|---|---|---| +| full version | `1.4.0` | This exact release. Never moves. Use it to deploy. | +| minor version | `1.4` | Moves to the newest `1.4.x`. | +| `latest` | `latest` | Moves to the newest release. | +| commit | `sha-3f2a9c1` | The commit the image was built from. | + +Raise the version for every image you publish: the last number for a fix, the middle one for a new function, the first one for a change that needs a new configuration or breaks something for its users. Do not push a published full version again with different content. + +### Log in + +1. In Gitea, open **Settings → Applications → Access Tokens** and create a token. Scope `write:package` to push (it includes reading), `read:package` for a machine that only pulls. +2. Log in and give the token when asked for the password: + + podman login gitea.psi.ch -u + + In a script, pass the token on standard input with `--password-stdin` so it does not appear in the command line. + +### Push by hand + + podman tag myapp:dev gitea.psi.ch//myapp:1.0.0 + podman push gitea.psi.ch//myapp:1.0.0 + +Push further tags of the same image the same way (`1.0`, `latest`). + +### Publish automatically on a version tag + +The gfa-monitoring repository builds and publishes its image in Gitea Actions whenever a version tag is pushed (`.gitea/workflows/release.yml`). It works in two jobs: + +1. **guard** checks that the tag points at a commit on `master`, because a tag can be pushed from any commit. A tag elsewhere is refused. +2. **publish** logs in to `gitea.psi.ch` with a token from the repository secret `REGISTRY_TOKEN`, derives the four tags from the version tag, builds for `linux/amd64` and pushes. + +The built-in token of Gitea Actions has no package scope, so the push needs a token of its own: create one with `write:package` and store it in the repository under **Settings → Actions → Secrets** as `REGISTRY_TOKEN`. The publish job, trimmed to what a Python service needs: + + on: + push: + tags: ["v*"] + jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: gitea.psi.ch + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + - id: meta + uses: docker/metadata-action@v5 + with: + images: gitea.psi.ch/${{ gitea.repository }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=sha,prefix=sha-,format=short + type=raw,value=latest + - uses: docker/build-push-action@v5 + with: + context: . + push: true + platforms: linux/amd64 + tags: ${{ steps.meta.outputs.tags }} + +Copy the guard job from the gfa-monitoring workflow as well if releases must come from `master` only. A release is then: + + git tag -a v1.0.0 -m "Release 1.0.0" + git push origin v1.0.0 + +### Check the published image + +1. In Gitea, open the organisation and its **Packages** tab (`https://gitea.psi.ch//-/packages`). The image is listed with its tags. +2. On another machine, pull it and start it once: + + podman pull gitea.psi.ch//myapp:1.0.0 + podman run --rm gitea.psi.ch//myapp:1.0.0 + +### When build or push fails + +- **`unauthorized` on push or pull**: not logged in, or the token lacks `write:package` / `read:package`. In Gitea Actions: `REGISTRY_TOKEN` is not set; the built-in token cannot push. +- **`exec format error` when the container starts on the host**: the image was built for arm64. Build with `--platform linux/amd64`. +- **`invalid reference format`**: the image name contains upper-case letters. Use lower case. +- **Image too large, slow push and pull**: use a `-slim` base, `--no-cache-dir`, and a `.containerignore` that keeps `.git`, virtual environments and data out. +- **`(already exists)` when you push the Git tag `v1.0.0`**: that version has been released already. Raise the version. + +## 3. Run it on a container host + +A container host is a Controls server that runs containers; you get one by [requesting a server](../../2._Services_Portfolio/Services/02_computingandboot.md#how-to-request-a-machine-or-a-change) for your service. The pattern in use today: + +- Each container is a systemd unit that pulls the image and starts it with `podman run`, so it starts at boot and restarts when it stops. +- The unit file is kept in Git; Puppet installs it in `/etc/systemd/system/` through a [change to the machine](../../2._Services_Portfolio/Services/02_computingandboot.md#request-a-change-to-an-existing-machine). Nothing is started by hand. +- Ports with `-p`, data that must survive in a host directory with `-v`, secrets in an environment file on the host (`--env-file`), never in Git or the image. +- The unit names a full version tag. Updating is a new tag in the unit and a restart; rolling back is the previous tag. +- The output goes to the journal and from there to Elastic: read it with `journalctl -u myapp` on the host and in Kibana ([Logging](../../2._Services_Portfolio/Services/03_devops.md#logging)). + +A compact example unit: + + [Unit] + Description=myapp + After=network-online.target + + [Service] + ExecStartPre=-/usr/bin/podman rm -f myapp + ExecStartPre=/usr/bin/podman pull gitea.psi.ch//myapp:1.0.0 + ExecStart=/usr/bin/podman run --rm --name myapp --init -p 8000:8000 \ + -v /data/myapp:/app/data --env-file /etc/myapp/myapp.env \ + gitea.psi.ch//myapp:1.0.0 + ExecStop=/usr/bin/podman stop myapp + Restart=always + + [Install] + WantedBy=multi-user.target + +Today these units run as root. Planned: rootless Podman under a service account, Quadlet unit files, and deployment through the catalogue (`cas container deploy`, not implemented yet). Controls IT owns the container host, your group owns the image and what runs in it ([who is responsible for what](../../2._Services_Portfolio/Services/02_computingandboot.md#who-is-responsible-for-what)). + +Soft IOCs are planned to run as rootless Podman containers under systemd where they suit it, once Channel Access in containers has been validated. Until then they run on [soft IOC hosts](../../2._Services_Portfolio/Services/02_computingandboot.md#soft-ioc-hosts-and-hardware-bound-ioc-hosts). diff --git a/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg b/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg new file mode 100644 index 00000000..ec853592 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg @@ -0,0 +1,126 @@ + + Build and publish a container image + Step 1, source repository: Containerfile, .containerignore, requirements.txt and code in Git. Step 2, build: podman build --platform linux/amd64 makes the image. Step 3, tag: the image gets the name gitea.psi.ch/org/myapp with the tags 1.0.0, 1.0, latest and sha-commit. Step 4, push to the registry gitea.psi.ch, by hand with podman push or by Gitea Actions on a version tag v1.0.0. Last, a container host pulls the image and runs it with Podman under systemd. + + + + + + + + + + + + + BUILD AND PUBLISH + RUN + + + + + + + + 1 + 2 + 3 + 4 + + + + + + + + Source + Git repository + + Containerfile + .containerignore + requirements.txt + app.py + No secrets, + no host settings + + + + + + + + Build + Code + dependencies + become an image + + podman build + --platform + linux/amd64 + Test locally: + podman run + podman logs + podman stop + + + + + + + + Tag + Name and versions + gitea.psi.ch/ + <org>/myapp + + :1.0.0 + :1.0 + :latest + :sha-<commit> + + + + + + + + Push + Token: write:package + + By hand + podman push + + Gitea Actions + on git tag v1.0.0 + + Registry + gitea.psi.ch + + + + + + + + Container host + podman pull + podman run + in a systemd unit + Output goes to + the journal + +