This is a fantastic goal! Using Podman for runners, Alpine for small images, and uv for lightning-fast Python dependency management is a very modern and efficient setup.
Let's break down all the steps you need to perform.
Part 1: Setting up GitLab Runner using Podman
This involves installing Podman, registering your runner, and running it as a Podman container.
Prerequisites
- A GitLab project: You need a project on GitLab.com or your self-hosted GitLab instance.
- A machine to host the runner: This machine should have network access to your GitLab instance.
- Root/sudo privileges on the runner host machine to install Podman and manage services.
Step 1: Install Podman on your Runner Host
Podman is a daemonless container engine for developing, managing, and running OCI Containers on your Linux system.
# For Fedora/RHEL/CentOS
sudo dnf install -y podman
# For Debian/Ubuntu
sudo apt update
sudo apt install -y podman
# For Arch Linux
sudo pacman -Syu podman
# For macOS (using Homebrew)
# Note: Podman on macOS runs inside a VM (podman machine).
# For CI, a Linux host is generally preferred.
brew install podman
podman machine init
podman machine start
# Verify installation
podman --version
Step 2: Create a Directory for GitLab Runner Configuration
It's good practice to keep your runner's configuration and data in a dedicated directory.
sudo mkdir -p /srv/gitlab-runner/config
# Set appropriate permissions (e.g., owned by a non-root user, or 700 for root)
# If you plan to run podman-compose/podman run as a specific user, ensure they own this directory.
# For simplicity, let's assume root for now, but in production, use a dedicated user.
sudo chown -R $(whoami) /srv/gitlab-runner # Or a dedicated 'gitlab-runner' user
Step 3: Register your GitLab Runner
You'll use the gitlab-runner image to register your runner. This will create a config.toml file.
-
Get Registration Token:
- In your GitLab project, go to Settings > CI/CD.
- Expand Runners.
- Find the "New project runner" or "Register an instance runner" section to get your registration token and GitLab URL.
-
Run Registration Command:
# This command maps the config directory and runs the registration.
# Replace <YOUR_GITLAB_URL> and <YOUR_REGISTRATION_TOKEN>
podman run --rm -it \
-v /srv/gitlab-runner/config:/etc/gitlab-runner \
gitlab/gitlab-runner:latest \
register \
--url <YOUR_GITLAB_URL> \
--registration-token <YOUR_REGISTRATION_TOKEN> \
--executor docker \
--description "My Alpine/UV Podman Runner" \
--docker-image "docker:latest" \
--tag-list "podman,alpine,uv,python" \
--locked=false # Set to true if you want to lock it to specific projects
During registration, you'll be prompted for:
- GitLab instance URL: (Already provided by
--url)
- Registration token: (Already provided by
--registration-token)
- Description: (Already provided by
--description)
- Tags: (Already provided by
--tag-list)
- Executor:
docker (Already provided by --executor)
- Default Docker image:
docker:latest (This is for the CI jobs, not the runner itself. We will override this in .gitlab-ci.yml.)
After successful registration, you should have a config.toml file in /srv/gitlab-runner/config.
-
Adjust config.toml (Crucial for Podman Socket):
Edit /srv/gitlab-runner/config/config.toml and add the following lines under the [[runners.docker]] section. This allows the docker executor to use the host's Podman socket.
[[runners]]
name = "My Alpine/UV Podman Runner"
url = "<YOUR_GITLAB_URL>"
token = "<YOUR_RUNNER_TOKEN>" # This is different from the registration token!
executor = "docker"
[runners.docker]
tls_verify = false
image = "docker:latest" # Default image for jobs
privileged = true # Often needed for some CI operations, or for 'dind' style if running docker inside containers (though we avoid dind here)
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
volumes = ["/cache"]
# --- ADD THESE LINES ---
host_services_mapping = { "/var/run/podman/podman.sock" = "/var/run/podman/podman.sock" }
# Or, if using an older runner or direct volume mapping:
# volumes = ["/var/run/podman/podman.sock:/var/run/docker.sock"] # Map Podman socket to Docker socket path in container
# Note: /var/run/docker.sock is the path the GitLab Runner 'docker' executor expects inside the container.
# It gets mapped to the actual Podman socket on the host.
# Ensure your Podman socket exists and is accessible: `ls -l /var/run/podman/podman.sock`
# If it doesn't exist, enable/start podman.socket: `sudo systemctl enable --now podman.socket`
# -----------------------
shm_size = 0
Explanation for volumes mapping: The GitLab Runner docker executor, by default, tries to communicate with a Docker daemon via /var/run/docker.sock inside the runner's container. By mapping your host's Podman socket (/var/run/podman/podman.sock) to this expected path (/var/run/docker.sock) inside the runner container, you trick the runner into using Podman.
Step 4: Run your GitLab Runner with Podman Compose (Recommended)
Using podman-compose is similar to docker-compose and allows for easy management of the runner container.
-
Install podman-compose:
# For Fedora/RHEL/CentOS
sudo dnf install -y podman-compose
# For Debian/Ubuntu (might be `python3-podman-compose` or similar)
sudo apt install -y podman-compose
# Or via pip (ensure you have pip installed)
pip install podman-compose
-
Create a podman-compose.yml file:
In /srv/gitlab-runner/, create podman-compose.yml:
version: '3.8'
services:
gitlab-runner:
image: gitlab/gitlab-runner:latest
container_name: gitlab-runner
restart: always
volumes:
- /srv/gitlab-runner/config:/etc/gitlab-runner
# Map the host's Podman socket to the path the runner expects
- /run/podman/podman.sock:/var/run/docker.sock
# Cache volume (optional, for persistent CI caches across runner restarts)
- /srv/gitlab-runner/cache:/home/gitlab-runner/cache:rw
environment:
# Optional: Set a specific user for the runner process inside the container
# If not set, it runs as root, which is generally not recommended for security.
# USER_UID: "1000" # Replace with your user's UID (e.g., `id -u youruser`)
# USER_GID: "1000" # Replace with your user's GID (e.g., `id -g youruser`)
# You might need to adjust permissions on /srv/gitlab-runner/config and cache
# if running as a non-root user.
ports:
- "8093:8093" # Optional: if you need to access runner metrics or API
# To make sure it can talk to the Podman daemon
# This isn't strictly necessary if the socket is mapped, but can help
# for specific use cases or troubleshooting.
# user: root # Ensure root if you need full access to socket (or setup proper permissions)
Important Note on user: root vs USER_UID/USER_GID:
- If you're mapping
/run/podman/podman.sock and the socket is only accessible by root or a specific group (e.g., podman group), the container user needs appropriate permissions.
- Running the runner container as
root (default if USER_UID/USER_GID are not set) is simpler for setup but less secure.
- For production, create a dedicated
gitlab-runner user on your host, ensure that user is in the podman group (sudo usermod -aG podman youruser), and then run podman-compose as that user. Or, set USER_UID/USER_GID in podman-compose.yml to map to an appropriate user ID.
-
Part 2: Prepare your Python Package
Let's set up a minimal Python package structure.
Example Project Structure
my_python_package/
├── src/
│ └── my_package/
│ ├── __init__.py
│ └── main.py
├── tests/
│ └── test_main.py
├── pyproject.toml
└── .gitlab-ci.yml
File Contents
-
src/my_package/__init__.py
__version__ = "0.1.0"
-
src/my_package/main.py
def greet(name: str) -> str:
"""Returns a greeting message."""
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
"""Adds two numbers."""
return a + b
if __name__ == "__main__":
print(greet("World"))
print(f"2 + 3 = {add(2, 3)}")
-
tests/test_main.py
import pytest
from my_package.main import greet, add
def test_greet():
assert greet("Alice") == "Hello, Alice!"
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
-
pyproject.toml
This modern standard defines your project. We'll use setuptools for building and pytest for testing.
[project]
name = "my-python-package"
version = "0.1.0"
description = "A simple example Python package"
readme = "README.md"
requires-python = ">=3.8"
license = { file = "LICENSE" } # Create a simple LICENSE file, e.g., MIT
authors = [
{ name = "Your Name", email = "your.email@example.com" },
]
keywords = ["example", "gitlab-ci", "uv", "python"]
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
dependencies = [] # Add any runtime dependencies here, e.g., "requests>=2.0"
[project.optional-dependencies]
dev = [
"pytest",
"uv", # uv is needed for local development, but not strictly for the deployed package
"wheel",
"twine",
]
[project.urls]
Homepage = "https://gitlab.com/your-namespace/my-python-package"
"Bug Tracker" = "https://gitlab.com/your-namespace/my-python-package/-/issues"
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.pytest.ini_options]
pythonpath = ["src"]
Create a simple README.md and LICENSE file as well.
Part 3: Create a Custom CI Docker Image (Optional but Highly Recommended)
While you could install Python and uv in each job, pre-building a custom image saves a lot of time on each CI run.
Dockerfile
Create this file in your project root, e.g., ci_image.Dockerfile.
# Use an Alpine base image
FROM alpine:3.19
# Install build-time dependencies for Python and uv
RUN apk add --no-cache \
python3 \
py3-pip \
git \
build-base \
# Needed for uv build if your package has C extensions
# python3-dev \
# libffi-dev \
# openssl-dev \
# cargo \
# If using specific databases, add their client libs here:
# mariadb-dev (for MySQL)
# postgresql-dev (for PostgreSQL)
# Install uv (using pip, as a standalone uv release for alpine might not be stable or widely available)
# As of uv 0.1.15, pip-installing uv works and is self-contained.
RUN pip install --no-cache-dir uv
# Set up uv cache directory
ENV UV_CACHE_DIR=/root/.uv/cache
# Create a non-root user (optional but good practice)
RUN adduser -D ciuser
USER ciuser
WORKDIR /home/ciuser
# Example of setting up a PATH to include things installed by uv into a venv if needed
# ENV PATH="/home/ciuser/.venv/bin:$PATH"
# Set a default command (optional)
# CMD ["python3"]
Build and Push the Image
You'll need a container registry (like GitLab Container Registry, Docker Hub, or Google Container Registry). For GitLab CI, GitLab Container Registry is ideal.
-
Login to GitLab Container Registry:
podman login registry.gitlab.com -u <your_gitlab_username>
# You'll be prompted for your GitLab Personal Access Token (PAT)
# Ensure the PAT has `read_registry` and `write_registry` scopes.
-
Build the Image:
podman build -t registry.gitlab.com/<your_gitlab_namespace>/<your_project_name>/ci-python-uv:latest -f ci_image.Dockerfile .
Replace <your_gitlab_namespace> with your username or group name.
Replace <your_project_name> with your project's slug (e.g., my-python-package).
-
Push the Image:
podman push registry.gitlab.com/<your_gitlab_namespace>/<your_project_name>/ci-python-uv:latest
Part 4: Configure GitLab CI (.gitlab-ci.yml)
This is the heart of your CI/CD pipeline. Create .gitlab-ci.yml in your project root.
# Use your custom built image
image: registry.gitlab.com/<your_gitlab_namespace>/<your_project_name>/ci-python-uv:latest
variables:
# Path to the uv cache directory.
# This should match what's set in the Dockerfile if you used it,
# or where uv stores its cache by default.
UV_CACHE_DIR: "$CI_PROJECT_DIR/.uv_cache"
# Set the Python path for your source code
PYTHONPATH: "$CI_PROJECT_DIR/src"
# Location for the virtual environment (uv venv creates .venv by default)
VIRTUAL_ENV_PATH: "$CI_PROJECT_DIR/.venv"
# Define where pytest will output its JUnit XML report
JUNIT_XML_REPORT: "test-results.xml"
stages:
- build
- test
- release
# Cache dependencies
cache:
key: ${CI_COMMIT_REF_SLUG} # Cache per branch/tag
paths:
- .uv_cache/ # The uv cache
- .venv/ # The virtual environment created by uv
policy: pull-push # Pull existing cache, then push updated cache
.install_deps: &install_deps_template
before_script:
- echo "--- Setting up Python environment with uv ---"
- uv venv $VIRTUAL_ENV_PATH # Create a virtual environment
- source $VIRTUAL_ENV_PATH/bin/activate # Activate it
- echo "--- Installing project dependencies and dev dependencies ---"
# Install the project itself in editable mode and its dependencies
# Then install optional dev dependencies (like pytest, wheel, twine)
- uv pip install .[dev]
build_package:
stage: build
# Use the template for dependency installation
<<: *install_deps_template
script:
- echo "--- Building the Python package ---"
- uv build --sdist --wheel . # Build source distribution and wheel
artifacts:
paths:
- dist/
expire_in: 1 week
test_package:
stage: test
needs: ["build_package"] # This job needs the artifacts from build_package
# Use the template for dependency installation
<<: *install_deps_template
script:
- echo "--- Running tests ---"
- uv pip install dist/*.whl # Install the built wheel for testing
- pytest --junitxml=$JUNIT_XML_REPORT tests/
artifacts:
when: always
reports:
junit: $JUNIT_XML_REPORT
paths:
- $JUNIT_XML_REPORT
expire_in: 1 day
# This job will deploy your package, e.g., to PyPI or a private registry.
# It only runs when a new tag is pushed.
deploy_package:
stage: release
needs: ["test_package"]
# Use the template for dependency installation, but only for twine, etc.
<<: *install_deps_template
script:
- echo "--- Deploying package to PyPI/registry ---"
# To upload to PyPI, you'll need TWINE_USERNAME and TWINE_PASSWORD as CI/CD variables
# (Settings > CI/CD > Variables). For security, use a project-specific token.
- twine upload --repository-url https://upload.pypi.org/legacy/ dist/*.whl
rules:
- if: $CI_COMMIT_TAG
when: on_success
GitLab CI/CD Variables
Go to your GitLab project: Settings > CI/CD > Variables.
Add the following variables (for deployment):
TWINE_USERNAME: __token__ (for PyPI token) or your PyPI username.
TWINE_PASSWORD: Your PyPI API token (recommended) or password.
- Protect variable: Yes
- Mask variable: Yes
Next Steps and Considerations
-
Commit and Push:
Commit all your files (src/, tests/, pyproject.toml, ci_image.Dockerfile, .gitlab-ci.yml) and push them to your GitLab repository.
-
Monitor Pipelines:
Go to CI/CD > Pipelines in your GitLab project. You should see a pipeline running, executing the build and test stages.
-
Local Testing:
-
Security:
- Runner User: As mentioned, run
gitlab-runner as a dedicated non-root user on your host.
- CI/CD Variables: Always use protected and masked CI/CD variables for sensitive information like API tokens.
- Image Security: Regularly update your custom CI image to patch vulnerabilities.
-
Further Customization:
- More Stages: Add stages for linting, security scanning, static analysis, etc.
- Notifications: Configure CI/CD notifications.
- Review Apps/Environments: If your package is part of a larger application, consider deploying review apps.
- Version Bumping: Automate version bumping based on git tags or commit messages.
This comprehensive guide should get you from zero to a fully functional GitLab CI/CD pipeline for your Python package, leveraging the efficiency of Podman, Alpine, and uv!