Skip to main content

core

Write Dockerfiles and Compose files, build and run containers, and store config and secrets.

DockerFile

Several functions on this page take keyword arguments and pass them on to a command-line tool, and mk_flags does the conversion. A one-letter keyword becomes a short flag, so d=True gives -d and f='x' gives -f x. A longer one becomes a long flag with underscores turned into hyphens, so remove_orphans=True gives --remove-orphans and name='web' gives --name=web. Keywords set to False or None are left out, and positional arguments come first. With short=False, every keyword becomes a long flag.


source

mk_flags

def mk_flags(
    *a, short:bool=True, sym:str='=', **kw
):

Turn keyword arguments into command-line flags: one-letter keys become -k [value] and longer keys --key[=value].

Dockerfile instructions

A Dockerfile is a list of instructions, one per line, each starting with a keyword such as FROM, RUN or COPY. The private helpers below (_from, _run, _copy and so on) each format one instruction. They take care of the details that are easy to get wrong by hand: joining an image and its tag, writing a command list in the JSON form Docker expects, and chaining several shell commands into a single RUN with &&. You do not call them directly; the Dockerfile methods do.

The tests after the helpers show the exact line each one writes.

assert _instr('RUN', 'echo hello') == 'RUN echo hello'
assert _from('python', '3.11') == 'FROM python:3.11'
assert _from('ubuntu', as_='builder') == 'FROM ubuntu AS builder'
assert _from('alpine') == 'FROM alpine'
assert _run('apt-get update') == 'RUN apt-get update'
r = _run(['apt-get update', 'apt-get install -y curl'])
assert 'apt-get update && ' in r
assert 'apt-get install -y curl' in r
assert _apt_install('curl', 'wget', y=True) == 'RUN apt-get update && apt-get install -y curl wget && rm -rf /var/lib/apt/lists/*'
assert _apt_install('git', clean=False) == 'RUN apt-get update && apt-get install git'
assert _cmd(['python', 'app.py']) == 'CMD ["python", "app.py"]'
assert _cmd('echo hello') == 'CMD echo hello'
assert _copy('.', '/app') == 'COPY . /app'
assert _copy('/build/out', '/app', from_='builder') == 'COPY --from=builder /build/out /app'
assert _copy('app/', '.', link=True) == 'COPY --link app/ .'
assert _copy('/app', '/app', from_='builder', link=True) == 'COPY --from=builder --link /app /app'
assert _workdir('/app') == 'WORKDIR /app'
assert _env('PATH', '/usr/local/bin') == 'ENV PATH=/usr/local/bin'
assert _env('DEBIAN_FRONTEND=noninteractive') == 'ENV DEBIAN_FRONTEND=noninteractive'
assert _expose(8080) == 'EXPOSE 8080'
assert _entrypoint(['python', '-m', 'flask']) == 'ENTRYPOINT ["python", "-m", "flask"]'
assert _arg('VERSION', '1.0') == 'ARG VERSION=1.0'
assert _arg('VERSION') == 'ARG VERSION'
assert _label(version='1.0', maintainer='me') == 'LABEL version="1.0" maintainer="me"'
assert _volume('/data') == 'VOLUME /data'
assert _volume(['/data', '/logs']) == 'VOLUME ["/data", "/logs"]'
assert _shell(['/bin/bash', '-c']) == 'SHELL ["/bin/bash", "-c"]'
assert 'CMD curl' in _healthcheck('curl -f http://localhost/', i='30s')
assert _healthcheck('curl localhost', i='30s', t='10s') == 'HEALTHCHECK --interval=30s --timeout=10s CMD curl localhost'
assert _healthcheck('curl localhost') == 'HEALTHCHECK CMD curl localhost'
assert _on_build(_run('echo triggered')) == 'ONBUILD RUN echo triggered'

The Dockerfile builder

Dockerfile holds the instruction lines in order. It has one method per Dockerfile keyword, named in lower case, and each method returns a new Dockerfile with the line added, so calls chain. print shows the file, and save writes it, to ./Dockerfile by default. A keyword without its own method still works: df.maintainer('me') adds MAINTAINER me, and df('healthcheck', 'NONE') does the same by name.

run_mount adds a RUN line with a --mount option. The default is a cache mount, a folder such as pip’s download cache that Docker keeps between builds; give its path as target.

_parse, below, reads Dockerfile text into a list of lines. It joins lines continued with a backslash and drops blank lines and comments, and Dockerfile.load uses it.

parsed = _parse("# comment\nFROM python:3.11\nRUN apt-get update && \\\n    apt-get install -y curl\nCOPY . /app")
print(parsed)
assert len(parsed) == 3
assert parsed[0] == 'FROM python:3.11'
assert 'apt-get install -y curl' in parsed[1]
['FROM python:3.11', 'RUN apt-get update && apt-get install -y curl', 'COPY . /app']

source

Dockerfile

def Dockerfile(
    items:NoneType=None, *rest, use_list:bool=False, match:NoneType=None
):

Build a Dockerfile one instruction at a time; each method returns a new Dockerfile.

df = (Dockerfile().from_('python:3.11-slim')
    .run('pip install flask')
    .copy('.', '/app')
    .workdir('/app')
    .expose(5000)
    .cmd(['python', 'app.py']))

expected = """FROM python:3.11-slim
RUN pip install flask
COPY . /app
WORKDIR /app
EXPOSE 5000
CMD [\"python\", \"app.py\"]"""

print(df)
assert str(df) == expected
FROM python:3.11-slim
RUN pip install flask
COPY . /app
WORKDIR /app
EXPOSE 5000
CMD ["python", "app.py"]
df = (Dockerfile().from_('python:3.12-slim')
    .run_mount('pip install -r requirements.txt', target='/root/.cache/pip')
    .run_mount('uv sync --frozen', target='/root/.cache/uv')
    .run_mount('apt-get install -y curl', type='cache', target='/var/cache/apt'))
s = str(df)
assert "RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt" in s
assert "RUN --mount=type=cache,target=/root/.cache/uv uv sync --frozen" in s
print(df)
FROM python:3.12-slim
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
RUN --mount=type=cache,target=/root/.cache/uv uv sync --frozen
RUN --mount=type=cache,target=/var/cache/apt apt-get install -y curl

A multi-stage build. Each from_ starts a new stage, and copy(from_=...) takes files from an earlier one:

df = (Dockerfile().from_('golang:1.21', as_='builder')
    .workdir('/src')
    .copy('.', '.')
    .run('go build -o /app')
    .from_('alpine')
    .copy('/app', '/app', from_='builder')
    .cmd(['/app']))

assert 'FROM golang:1.21 AS builder' in str(df)
assert 'COPY --from=builder /app /app' in str(df)
print(df)
FROM golang:1.21 AS builder
WORKDIR /src
COPY . .
RUN go build -o /app
FROM alpine
COPY --from=builder /app /app
CMD ["/app"]

Pass a list to run to join several shell commands with && into one RUN line, which gives one image layer instead of several:

df = (Dockerfile().from_('ubuntu:22.04').run(['apt-get update', 'apt-get install -y python3', 'rm -rf /var/lib/apt/lists/*']))
print(df)
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 && rm -rf /var/lib/apt/lists/*

Loading an existing Dockerfile

Dockerfile.load reads a Dockerfile from disk, so you can start from a file you already have and add to it. save writes the file and returns the Dockerfile itself, not the path.

import tempfile
tmp = tempfile.mkdtemp()
Path(f'{tmp}/Dockerfile').write_text("# My app\nFROM python:3.11-slim\nRUN apt-get update && \\\n    apt-get install -y curl\nCOPY . /app\nCMD [\"python\", \"app.py\"]")

df = Dockerfile.load(f'{tmp}/Dockerfile')
assert len(df) == 4
assert df[0] == 'FROM python:3.11-slim'

p = f'{tmp}/Dockerfile'
df.save(p)
assert Path(p).exists()

df2 = df.run('echo hi')
assert len(df2) == 5
print(df)
FROM python:3.11-slim
RUN apt-get update && apt-get install -y curl
COPY . /app
CMD ["python", "app.py"]

Build, run, test

These functions wrap the Docker command-line tool for the usual loop: build an image from a Dockerfile, run a container from it, and check that a command succeeds inside it. They need Docker installed and its daemon running.

Cli is a small base class for wrapping a command-line tool, and Docker is the one for docker. Any attribute is a subcommand, with underscores turned into hyphens, and keywords become flags: Docker().ps(a=True) runs docker ps -a. Calling the object directly also works, as in Docker()('logs', 'web'). Each call returns what the command printed and raises IOError if it fails. Docker().compose(...) runs a compose subcommand, using the older standalone docker-compose if it is installed and docker compose otherwise.

Docker(no_creds=True) runs docker with a copy of your Docker config that has the credential helpers (credsStore and credHelpers) taken out, kept in ~/.fastops/config. It applies only when the DOCKR_RUNTIME environment variable is unset or set to docker.

Dockerfile.build saves the Dockerfile into the folder path and builds it with docker compose build. That command uses the daemon’s BuildKit and does not need the buildx plugin. build returns the tag. test runs a command in a throwaway container and returns True if the command exits with status 0. drun runs a container and returns its output. With detach=True it starts the container in the background and returns its ID. The ports dictionary maps container ports to host ports.

ports entry container port host port
{'80/tcp': 8080} 80 8080

With check=True, the default, drun watches a detached container for up to two seconds. It raises RuntimeError, with the container’s logs, if the container stops in that time.


source

Cli

def Cli(
    *args, **kwargs
):

Base class for wrapping a command-line tool: calling it runs a subcommand with keywords as flags, and any attribute is a subcommand.


source

Docker

def Docker(
    no_creds:bool=False
):

Run docker commands from Python; no_creds=True uses a copy of the Docker config without credential helpers.


source

drun

def drun(
    img:str, detach:bool=False, ports:NoneType=None, name:NoneType=None, remove:bool=False, command:NoneType=None,
    check:bool=True
):

Run a container from img and return its output, or its ID if detach=True; with check=True a detached container that stops at once raises RuntimeError.


source

test

def test(
    img_or_tag:str, cmd
):

Return True if cmd exits with status 0 in a throwaway container from img_or_tag.


source

Dockerfile.build

def build(
    df:__main__.Dockerfile, tag:str=None, path:str='.', no_creds:bool=False, fn:str='Dockerfile'
):

Save the Dockerfile into path as fn and build it with docker compose build, returning tag.

from fastcore.test import test_fail, test_eq

Here a detached container exits straight away. drun raises RuntimeError with its logs instead of returning the ID of a container that is already gone:

try:
    drun('alpine', detach=True, command=['sh', '-c', 'exit 1'], check=True)
    print('NO EXCEPTION RAISED')
except Exception as e:
    print(f'Exception type: {type(e).__name__}')
    print(f'Exception message: {str(e)[:300]}')
Exception type: RuntimeError
Exception message: Container '578084b28be52a324fd50dc429702be1a47132fc89cfe73c9525251755bbfe30' failed to start.

Convenience functions

Short wrappers for the commands used most. containers lists container names, running ones only unless you pass all=True. images lists images as repository:tag. logs returns the last n lines of a container’s log. stop, rm and rmi stop a container, remove a container and remove an image, and force=True adds -f to the last two.


source

rmi

def rmi(
    nm, force:bool=False
):

source

rm

def rm(
    nm, force:bool=False
):

source

logs

def logs(
    nm, n:int=10
):

source

stop

def stop(
    nm
):

source

images

def images():

source

containers

def containers(
    all:bool=False
):

Example: a FastHTML app with uv

A Dockerfile for a FastHTML app. It installs curl and sqlite3 with apt, exports the dependencies from pyproject.toml with uv and installs them with pip, and declares /app/data as a volume so the app’s data is kept outside the container:

df = (Dockerfile().from_('python', '3.12-slim')
    .apt_install('curl', 'sqlite3', y=True)
    .run('pip install uv')
    .workdir('/app')
    .copy('pyproject.toml', '.')
    .run('uv export --no-hashes -o requirements.txt && pip install -r requirements.txt')
    .copy('.', '.')
    .volume('/app/data')
    .expose(5001)
    .cmd(['python', 'main.py']))

print(df)
FROM python:3.12-slim
RUN apt-get update && apt-get install -y curl sqlite3 && rm -rf /var/lib/apt/lists/*
RUN pip install uv
WORKDIR /app
COPY pyproject.toml .
RUN uv export --no-hashes -o requirements.txt && pip install -r requirements.txt
COPY . .
VOLUME /app/data
EXPOSE 5001
CMD ["python", "main.py"]

Building and running needs Docker, so the next cell is skipped in the docs build. It builds a tiny image, runs it, prints what it printed, and removes it:

tmp = tempfile.mkdtemp()
df = Dockerfile().from_('alpine').run('echo hello > /greeting.txt').cmd(['cat', '/greeting.txt'])
tag = df.build(tag='fastops-test:hello', path=tmp, no_creds=True)
print(f'Built: {tag}')
out = drun(tag, remove=True)
print(f'Output: {out}')
rmi(tag, force=True)
print('Cleaned up.')
Built: fastops-test:hello
Output: hello
Cleaned up.

End to end: a FastHTML todo app

This example writes a small todo app to a temporary folder, builds it into an image, runs it, adds three todos through its web form and reads them back from its JSON API. The first cell writes the app and defines two helpers for later cells: test_post adds and lists the todos, and cleanup removes the container and the image.

app_dir = Path(tempfile.mkdtemp()) / 'fasthtml-todo'
app_dir.mkdir()

code = {'main.py' :'''
from json import dumps
from fasthtml.common import *

db = database('data/todos.db')
todos = db.t.todos
if todos not in db.t: todos.create(id=int, title=str, done=bool, pk='id')
Todo = todos.dataclass()

app, rt = fast_app(live=False)

@rt('/')
def get():
    items = [Li(f"{'✓' if t.done else '○'} {t.title}", id=f'todo-{t.id}') for t in todos()]
    return Titled('Todos',
        Ul(*items),
        Form(Input(name='title', placeholder='New todo...'), Button('Add'), action='/add', method='post'))

@rt('/add', methods=['post'])
def post(title: str):
    todos.insert(Todo(title=title, done=False))
    return Redirect('/')

@rt('/api/todos')
def api():
    data = [dict(id=t.id, title=t.title, done=t.done) for t in todos()]
    return Response(dumps(data), media_type='application/json')

serve(host='0.0.0.0', port=5001)
''', 'requirements.txt':'python-fasthtml\n'}

for k,v in code.items(): Path(app_dir / k).write_text(v)

def test_post(url='http://localhost:5001'):
    for t in ['Buy milk', 'Write docs', 'Ship fastops']: urlread(f'{url}/add', title=t)
    for t in urljson(f'{url}/api/todos'): print(f"  {'✓' if t['done'] else '○'} {t['title']}")

def cleanup(nm, tag):
    rm(nm, force=True)
    rmi(tag, force=True)

print(f'App dir: {app_dir}')
print('Files:', os.listdir(app_dir))
App dir: /var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmphf0q8sp4/fasthtml-todo
Files: ['requirements.txt', 'main.py']
df = (Dockerfile()
    .from_('python', '3.12-slim')
    .workdir('/app')
    .copy('requirements.txt', '.')
    .run('pip install --no-cache-dir -r requirements.txt')
    .copy('.', '.')
    .volume('/app/data')
    .expose(5001)
    .cmd(['python', 'main.py']))

print(df)
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
VOLUME /app/data
EXPOSE 5001
CMD ["python", "main.py"]
import time
from fastcore.net import urlread, urljson

Building and running the app needs Docker, so the next cell is skipped in the docs build. It removes any container left from an earlier run, starts the app on port 5001, calls test_post, and cleans up:

tag = 'fastops-fasthtml:latest'
name = 'fastops-fasthtml-demo'
df.build(tag=tag, path=str(app_dir), no_creds=True)
print(f'Built: {tag}')
for cid in Docker()('ps', '-aq', '--filter', f'ancestor={tag}').splitlines(): rm(cid, force=True)
rm(name, force=True)
cid = drun(tag, detach=True, ports={'5001/tcp': 5001}, name=name, check=True)
print(f'Container: {cid[:12]}')
time.sleep(3)

try: test_post()
except Exception as e:
    print(f'Test failed: {e}')
    print(f'\nLogs:')
    print(logs(name, n=3))
finally: cleanup(name, tag)
print('Cleaned up.')
Built: fastops-fasthtml:latest
Container: bf1125b54374
  ○ Buy milk
  ○ Write docs
  ○ Ship fastops
Cleaned up.

Docker Compose

A Compose file, docker-compose.yml, lists the services that make up an app and how they connect, and docker compose up starts them all together. A service is one container in that stack, described by the image it runs or the folder it is built from, plus its ports, environment variables, volumes and the other services it needs.

Service

service turns keyword arguments into the dict for one service. ports and volumes can be dicts, {host_port: container_port} and {volume_or_host_path: container_path}, which become Compose’s "a:b" strings, and env can be a dict, which becomes KEY=value strings. Lists are kept as they are. A Dockerfile passed as build becomes build: .. Save that Dockerfile in the folder the Compose file runs from. Arguments left as None are omitted, and any other keyword, such as restart or networks, is copied in unchanged. You will usually call it through Compose.svc.


source

service

def service(
    image:NoneType=None, build:NoneType=None, ports:NoneType=None, env:NoneType=None, volumes:NoneType=None,
    depends_on:NoneType=None, command:NoneType=None, **kw
):

Return the dict for one Compose service, turning ports, env and volumes dicts into Compose’s list form.


source

dict2str

def dict2str(
    d:dict, sep:str=':'
):
d = service(image='nginx', ports={80: 80})
assert d['image'] == 'nginx'
assert d['ports'] == ['80:80']
d = service(image='postgres:15', env={'POSTGRES_PASSWORD': 'secret'}, volumes={'pgdata': '/var/lib/postgresql/data'})
assert d['environment'] == ['POSTGRES_PASSWORD=secret']
assert d['volumes'] == ['pgdata:/var/lib/postgresql/data']

Compose

Compose builds the whole file. svc adds a service, passing its keywords to service. network and volume declare a network or a named volume, with any keywords as its settings. Each call returns a new Compose, so calls chain. print shows the YAML, to_dict returns the same thing as a dict, and save writes it, to docker-compose.yml by default. Compose.load reads an existing file back in.

up saves the file and runs docker compose up, detached unless you pass detach=False. down and logs run docker compose down and docker compose logs on the file that is already saved. Extra keywords to all three become flags in the way mk_flags describes, and no_creds=True works as it does for Docker.


source

Compose

def Compose(
    items:NoneType=None, *rest, use_list:bool=False, match:NoneType=None
):

Build a docker-compose.yml from services, networks and volumes; each method returns a new Compose.

dc = (Compose()
      .svc('web', image='nginx', ports={80: 80}, networks=['backend'])
      .svc('redis', image='redis:alpine')
      .svc('db', image='postgres:15', env={'POSTGRES_PASSWORD': 'secret'},
           volumes={'pgdata': '/var/lib/postgresql/data'})
      .network('backend').volume('pgdata'))

d = dc.to_dict()
assert 'networks' in d
assert 'volumes' in d
assert 'pgdata' in d['volumes']
print(dc)
services:
  web:
    image: nginx
    ports:
    - 80:80
    networks:
    - backend
  redis:
    image: redis:alpine
  db:
    image: postgres:15
    environment:
    - POSTGRES_PASSWORD=secret
    volumes:
    - pgdata:/var/lib/postgresql/data
networks:
  backend: null
volumes:
  pgdata: null

Compose up, test, down, and load

The todo app from above as a one-service stack, with a named volume for its data. The cell after the next one is skipped in the docs build. It starts the stack from the app folder, posts the todos, takes the stack down along with its volumes and images, and reads the file back with Compose.load:

dc = (Compose()
      .svc('app',
           build='.',
           ports={5001: 5001},
           restart='unless-stopped',
           volumes={'app_data': '/app/data'})
      .volume('app_data')).save(app_dir/'docker-compose.yml')
assert (app_dir/'docker-compose.yml').exists()
print((app_dir/'docker-compose.yml').read_text())
services:
  app:
    ports:
    - 5001:5001
    build: .
    volumes:
    - app_data:/app/data
    restart: unless-stopped
volumes:
  app_data: null
from fastcore.foundation import working_directory
with working_directory(app_dir) as w:
    dc.up(no_creds=True)
    time.sleep(3)
    test_post()
    dc.down(v=True,rmi='all',remove_orphans=True)
    print('\n Compose load test: \n')
    print(Compose.load())
  ○ Buy milk
  ○ Write docs
  ○ Ship fastops

 Compose load test: 

services:
  app:
    ports:
    - 5001:5001
    build: .
    volumes:
    - app_data:/app/data
    restart: unless-stopped
volumes:
  app_data: null

App builders

Five methods added to Dockerfile install dependencies: inst_uv, uv_deps, uv_project, with_uv and packages. The builders further down use them.

A single-stage Dockerfile installs dependencies in the final image. A multi-stage Dockerfile installs dependencies in a builder stage and copies the result into a separate runtime stage.

inst_uv is the single-stage way to install a Python project. It installs uv with pip, copies pyproject.toml in, runs uv sync --no-dev and puts the project’s .venv on the PATH. With req=True it copies requirements.txt instead and installs it into the system Python.

Three options make the single-stage install reproducible and quick to rebuild. lock=True copies uv.lock too and syncs with --frozen. The image then has exactly the versions in the lock file. bytecode=True compiles the installed packages to bytecode in the image. The app then does not compile them each time it starts. deps_first=True splits the install in two layers: uv_deps syncs the dependencies alone, then uv_project copies the project in and syncs it. Docker reuses the dependency layer until pyproject.toml or uv.lock changes. A code change rebuilds only the second half. mid runs commands between dependency installation and project installation, such as a download the app needs at run time. compile names source folders to compile to bytecode after the project sync.

The single-stage recipe pulls only from Docker Hub and installs uv with pip. The multi-stage recipe pulls uv’s image from ghcr.io, and GitHub’s registry answers some hosting providers’ addresses with 403 Forbidden for anonymous pulls. A Hetzner server building a Compose stack hit this. Use multistage=False, lock=True on such servers.

with_uv is the multi-stage way. It adds a build stage in uv’s image that installs the dependencies pinned in uv.lock, with uv’s cache kept between builds, and then starts the runtime stage from image. The caller copies the result across, as python_app does with copy(wd, wd, from_='builder').

packages installs system packages with apt-get. Pass the names as separate arguments, not as one list. With no names it does nothing. A builder can write .packages(*listify(pkgs)) without checking whether pkgs is empty.


source

Dockerfile.packages

def packages(
    *pkgs
):

Install system packages with apt-get, or do nothing when no packages are given.


source

Dockerfile.with_uv

def with_uv(
    uv_image, image, workdir
):

Add a uv build stage that installs the locked dependencies, then start the runtime stage from image.


source

Dockerfile.inst_uv

def inst_uv(
    req:bool=False, wd:str='/app', lock:bool=False, bytecode:bool=False, deps_first:bool=False, mid:NoneType=None,
    compile:NoneType=None
):

Install uv with pip and sync the project into a .venv, or install requirements.txt into the system Python with req=True.


source

Dockerfile.uv_project

def uv_project(
    lock:bool=True, wd:str='/app', compile:NoneType=None
):

Copy the project in, sync it, compile the compile folders to bytecode, and put the .venv on the PATH.


source

Dockerfile.uv_deps

def uv_deps(
    lock:bool=True, bytecode:bool=False
):

Install uv with pip and sync only the dependencies, from uv.lock with --frozen when lock, so the layer survives code changes.

Framework builders

Each builder returns a complete Dockerfile for one kind of project. Call it with no arguments for the defaults, or pass the keywords shown in its signature.

Function Default port What it writes
python_app 8000 a uv build stage, then python:3.13-slim with the app and its .venv
fasthtml_app 5001 python_app in one stage, running python app.py
fastapi_react 8000 a Node stage that builds the frontend, then a Python stage that serves it with uvicorn
go_app 8080 a Go build stage, then a distroless image with the binary
rust_app 8080 a Cargo build stage, then a distroless image with the binary
node_app 3000 one Node stage, or with static=True a build stage and a stage that serves dist/
detect_app depends looks at the project’s files and calls one of the above

In python_app, pkgs installs apt packages, pre runs commands after them, vols creates folders for volumes, and healthcheck adds a check on that path. The check uses curl when pkgs installs it, and otherwise a Python one-liner with urllib, since the slim image has no curl. ports=3 exposes three consecutive ports from port, for an app that runs one worker per port; the health check probes the first. With multistage=False it uses inst_uv in a single stage, and req=True then installs requirements.txt; req has no effect on the default two-stage build. multistage=False, lock=True is the locked single-stage recipe: dependencies first from uv.lock, then the project, with bytecode, mid and compile passed to inst_uv. fasthtml_app is python_app with port=5001, cmd=['python', 'app.py'] and multistage=False filled in by bind, and any of them can be overridden. fastapi_react expects the frontend in frontend/ with its build output in dist/, copies that to /app/static, runs uvicorn main:app, and by default adds a health check on /health, chosen the same way.

detect_app checks for Cargo.toml, then go.mod, then package.json (with or without Python files), then pyproject.toml (with or without python-fasthtml in it), then requirements.txt, and raises ValueError if it finds none of them.


source

detect_app

def detect_app(
    path:str='.', multistage:bool=True, **kw
):

Pick a builder from the files in path and return its Dockerfile; extra keywords go to that builder.


source

node_app

def node_app(
    port:int=3000, node_version:str='20', cmd:NoneType=None, build_cmd:str='npm run build', static:bool=False
):

Return a Dockerfile that runs a Node.js app, or with static=True builds it and serves dist/ with serve.


source

rust_app

def rust_app(
    port:int=8080, rust_version:str='1', binary:str='app', runtime:str='gcr.io/distroless/static',
    features:NoneType=None
):

Return a two-stage Dockerfile that builds a Rust binary with cargo build --release and runs it in a distroless image.


source

go_app

def go_app(
    port:int=8080, go_version:str='1.22', binary:str='app', runtime:str='gcr.io/distroless/static',
    cmd:NoneType=None, cgo:bool=False
):

Return a two-stage Dockerfile that compiles a Go binary and runs it in a distroless image.


source

fastapi_react

def fastapi_react(
    port:int=8000, node_version:str='20', frontend_dir:str='frontend', build_dir:str='dist',
    image:str='python:3.13-slim', pkgs:NoneType=None, healthcheck:str='/health', multistage:bool=False,
    uv_image:str='ghcr.io/astral-sh/uv:python3.13-bookworm'
):

Return a Dockerfile that builds a Node frontend and serves it from a Python app run with uvicorn; multistage=True adds a uv build stage.


source

python_app

def python_app(
    port:int=8000, cmd:NoneType=None, im:str='python:3.13-slim', wd:str='/app', pkgs:NoneType=None,
    vols:NoneType=None, multistage:bool=True, uv_image:str='ghcr.io/astral-sh/uv:python3.13-bookworm',
    healthcheck:NoneType=None, req:bool=False, lock:bool=False, bytecode:bool=False, ports:int=1, pre:NoneType=None,
    mid:NoneType=None, compile:NoneType=None
):

Return a Dockerfile for a uv-managed Python app: a uv build stage and a slim runtime by default, or one stage with multistage=False.

Builder tests

The cells below check the lines that each builder writes.

df = Dockerfile().from_('python:3.13-slim').workdir('/app').inst_uv()
s = str(df)
assert 'pip install uv' in s
assert 'uv sync --no-dev' in s
assert 'ENV PATH=/app/.venv/bin:$PATH' in s
assert 'COPY uv.lock' not in s
print('inst_uv OK')

df = Dockerfile().with_uv('ghcr.io/astral-sh/uv:python3.13-bookworm', 'python:3.13-slim', '/app')
s = str(df)
assert 'uv:python3.13-bookworm AS builder' in s
assert 'ENV UV_COMPILE_BYTECODE=1' in s and 'ENV UV_LINK_MODE=copy' in s
assert 'FROM python:3.13-slim' in s
print('build_uv OK')

assert len(Dockerfile().from_('alpine').packages()) == 1   # no-op
assert 'apt-get install -y curl' in str(Dockerfile().from_('alpine').packages('curl'))
print('packages OK')

df = Dockerfile().from_('python:3.13-slim').workdir('/app').inst_uv(req=True)
s = str(df)
assert 'pip install uv' in s
assert 'COPY requirements.txt .' in s
assert 'uv pip install --system -r requirements.txt' in s
assert 'pyproject.toml' not in s and 'uv sync' not in s
assert 'ENV PATH' not in s
print('inst_uv(req=True) OK')
df = python_app(); s = str(df)
assert 'uv:python3.13-bookworm AS builder' in s and 'ENV UV_COMPILE_BYTECODE=1' in s
assert 'COPY --from=builder /app /app' in s and 'ENV PATH=/app/.venv/bin:$PATH' in s
assert 'FROM python:3.13-slim' in s and 'EXPOSE 8000' in s and 'CMD ["python", "main.py"]' in s
print('python_app() multistage OK')

df = python_app(port=5001, multistage=False, pkgs=['libpq-dev', 'curl'], vols=['/app/data'], healthcheck='/health')
s = str(df)
assert 'pip install uv' in s
assert 'apt-get install -y libpq-dev curl' in s
assert 'ENV PATH=/app/.venv/bin:$PATH' in s
assert 'mkdir -p /app/data' in s and 'HEALTHCHECK' in s and 'EXPOSE 5001' in s
print('python_app() single-stage OK')

hc = 'HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD ["python", "-c", "import urllib.request; urllib.request.urlopen(\'http://localhost:8000/health\', timeout=4)"]'
for d in (python_app(healthcheck='/health'), python_app(multistage=False, lock=True, healthcheck='/health')): assert hc in str(d).splitlines() and 'curl' not in str(d)   # the slim image has no curl
assert 'CMD curl -f http://localhost:5001/health' in str(python_app(5001, pkgs=['curl'], healthcheck='/health'))   # unless the image installs it
assert 'urlopen(\'http://localhost:8000/health\'' in str(fastapi_react()) and 'curl' not in str(fastapi_react())
print('python_app() healthcheck without curl OK')

df = python_app(multistage=False, req=True); s = str(df)
assert 'COPY requirements.txt .' in s
assert 'uv pip install --system -r requirements.txt' in s
assert 'pyproject.toml' not in s
assert 'ENV PATH' not in s
print('python_app(req=True) OK')
df = python_app(port=5001, multistage=False, lock=True, bytecode=True, ports=3, pkgs=['curl'], vols=['/app/data'], healthcheck='/health',
                pre='curl -fsSL https://rclone.org/install.sh | bash', mid='.venv/bin/python -c "import x"', compile='src')
test_eq(str(df).splitlines(), ['FROM python:3.13-slim', 'WORKDIR /app', 'RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*',
    'RUN curl -fsSL https://rclone.org/install.sh | bash', 'RUN pip install uv', 'COPY pyproject.toml .', 'COPY uv.lock .',
    'RUN uv sync --frozen --no-dev --no-install-project --compile-bytecode', 'RUN .venv/bin/python -c "import x"', 'COPY . .',
    'RUN uv sync --frozen --no-dev && .venv/bin/python -m compileall -q src', 'ENV PATH=/app/.venv/bin:$PATH', 'RUN mkdir -p /app/data',
    'HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -f http://localhost:5001/health', 'EXPOSE 5001 5002 5003', 'CMD ["python", "main.py"]'])
s = str(Dockerfile().from_('python:3.13-slim').inst_uv(lock=True))
assert 'COPY uv.lock .' in s and 'RUN uv sync --frozen --no-dev' in s and '--no-install-project' not in s
s = str(python_app(multistage=False, lock=True))
assert s.count('COPY . .') == 1 and 'EXPOSE 8000' in s
test_eq(str(python_app(multistage=False, pre='echo hi')).splitlines()[2], 'RUN echo hi')
print('locked single stage OK')
df = fasthtml_app(); s = str(df)
assert 'EXPOSE 5001' in s and 'uv sync --no-dev' in s and 'CMD ["python", "app.py"]' in s
assert 'ENV PATH=/app/.venv/bin:$PATH' in s and 'AS builder' not in s
df2 = fasthtml_app(pkgs=['rclone'], vols=['/app/data'], healthcheck='/health'); s2 = str(df2)
assert 'rclone' in s2 and 'mkdir -p /app/data' in s2 and 'HEALTHCHECK' in s2
print('fasthtml_app() OK')

df = fastapi_react(); s = str(df)
assert s.count('FROM') == 2 and 'FROM node:20-slim AS frontend' in s
assert 'COPY --from=frontend /build/dist /app/static' in s and 'uvicorn' in s
print('fastapi_react() 2-stage OK')

df = fastapi_react(multistage=True); s = str(df)
assert s.count('FROM') == 3 and 'uv:python3.13-bookworm AS builder' in s
assert 'COPY --from=builder /app /app' in s and 'ENV PATH=/app/.venv/bin:$PATH' in s
assert 'COPY --from=frontend /build/dist /app/static' in s
print('fastapi_react() 3-stage OK')
df = go_app(); s = str(df)
assert 'FROM golang:1.22-alpine AS builder' in s and 'go mod download' in s
assert 'ENV CGO_ENABLED=0' in s and '-o /app' in s
assert 'FROM gcr.io/distroless/static' in s and 'CMD ["/app"]' in s
df2 = go_app(binary='srv'); s2 = str(df2)
assert '-o /srv' in s2 and 'COPY --from=builder /srv /srv' in s2 and 'CMD ["/srv"]' in s2
print('go_app() OK')

df = rust_app(); s = str(df)
assert 'FROM rust:1-slim-bookworm AS builder' in s and 'cargo build --release' in s
assert 'COPY --from=builder /src/target/release/app /app' in s and 'CMD ["/app"]' in s
df2 = rust_app(binary='myapp', features='postgres'); s2 = str(df2)
assert '--features postgres' in s2 and '/src/target/release/myapp' in s2
print('rust_app() OK')

df = node_app(); s = str(df)
assert 'FROM node:20-slim' in s and 'npm ci' in s and 'EXPOSE 3000' in s and 'CMD ["node", "index.js"]' in s
df2 = node_app(static=True); s2 = str(df2)
assert 'FROM node:20-slim AS builder' in s2 and 'npm run build' in s2
assert 'COPY --from=builder /app/dist .' in s2 and 'serve' in s2
print('node_app() OK')
go_app() OK
rust_app() OK
node_app() OK
def _tmp(files):
    d = Path(tempfile.mkdtemp())
    for f, c in files.items(): (d/f).write_text(c)
    return d

assert 'golang' in str(detect_app(_tmp({'go.mod': 'module x'})))
assert 'rust' in str(detect_app(_tmp({'Cargo.toml': '[package]'}))).lower()
assert 'EXPOSE 3000' in str(detect_app(_tmp({'package.json': '{}'})))
assert 'uvicorn' in str(detect_app(_tmp({'package.json': '{}', 'pyproject.toml': '[project]'})))
assert 'EXPOSE 5001' in str(detect_app(_tmp({'pyproject.toml': '[project]\ndependencies=["python-fasthtml"]'})))
assert 'EXPOSE 8000' in str(detect_app(_tmp({'pyproject.toml': '[project]'})))
s = str(detect_app(_tmp({'requirements.txt': 'flask\n'})))
assert 'uv pip install --system -r requirements.txt' in s and 'AS builder' not in s
try: detect_app(_tmp({'README.md': ''}))
except ValueError: pass
else: raise AssertionError('Expected ValueError')
print('detect_app() OK')

Config and Secrets

Non-secret config

Deploy scripts need values such as a server’s IP address or the path to an SSH key. env_set writes one to the file at the path FASTOPS_ENV. The default file is ~/.config/fastops/.env. env_set creates a missing file with the permissions in the table.

file mode access
0600 the owner reads and writes, nobody else has access

env_set also sets the value in os.environ. The running process sees the value at once. env_get reads os.environ first, then the file, and returns default if neither has the key. Both take path to use a different file. The test below uses a temporary one; the “not found” lines are python-dotenv reporting keys that are not in the file yet.


source

env_get

def env_get(
    key, path:NoneType=None, default:NoneType=None
):

Read key from os.environ, then the .env file, and return default if neither has it.


source

env_set

def env_set(
    key, value, path:NoneType=None
):

Save key=value in the fastops .env file, or the file at path, and in os.environ.

tmp = Path(tempfile.mkdtemp()) / '.env'
env_set('_FO_TEST_IP', '1.2.3.4', path=tmp)
assert os.environ['_FO_TEST_IP'] == '1.2.3.4'
assert env_get('_FO_TEST_IP', path=tmp) == '1.2.3.4'
env_set('_FO_TEST_IP', '1.2.3.4', path=tmp)
del os.environ['_FO_TEST_IP']
assert env_get('_FO_TEST_IP', path=tmp) == '1.2.3.4'
assert env_get('_FO_TEST_MISSING', path=tmp, default='fallback') == 'fallback'
env_set('_FO_TEST_IP', '5.6.7.8', path=tmp)
assert env_get('_FO_TEST_IP', path=tmp) == '5.6.7.8'
assert _FASTOPS_ENV is FASTOPS_ENV and FASTOPS_ENV.name == '.env'
print('env_set/env_get OK')
Key _FO_TEST_IP not found in /var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp2xqc3991/.env.
Key _FO_TEST_MISSING not found in /var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp2xqc3991/.env.
env_set/env_get OK

Secrets

secret_set and secret_get are for sensitive values such as API tokens and tunnel tokens. secret_set stores the value in the system keychain through the keyring package, for example the macOS Keychain or the Secret Service on Linux. Some machines have no keychain, for example a Linux desktop with no Secret Service, a server or a CI machine. There, secret_set writes the value in plain text to the .env file, sets the file mode to 0600 so that only you can read it, and issues a UserWarning that names the file. Pass save=True to also write the value to the .env file and set it in os.environ when the keychain works.

secret_set returns where the value went: {'keychain': True, 'file': None} for the keychain only, and the path of the .env file in file when the file holds a copy. An app can show this to the user.

secret_get looks in the keychain, then os.environ, then the .env file, and returns default if none of them has the key. On a server, the usual way to supply secrets is as environment variables, set at boot by cloud-init or a systemd EnvironmentFile=.


source

secret_get

def secret_get(
    key, service:str='fastops', default:NoneType=None, path:NoneType=None
):

Read a secret from the keychain, then os.environ, then the .env file, and return default if none has it.


source

secret_set

def secret_set(
    key, value, service:str='fastops', save:bool=False, path:NoneType=None
):

Store a secret in the keychain, or in the 0600 .env file when there is none; save=True also writes the file and os.environ. Return where it went.

from keyring.backend import KeyringBackend
from keyring.backends import fail

The tests below never touch the real keychain or the real .env file. MemKeyring is a keychain held in memory, and FASTOPS_ENV points at a temporary file.

class MemKeyring(KeyringBackend):
    'A keychain held in memory, for tests.'
    priority = 1
    def __init__(self): super().__init__(); self.d = {}
    def get_password(self, s, k): return self.d.get((s,k))
    def set_password(self, s, k, v): self.d[(s,k)] = v
    def delete_password(self, s, k): self.d.pop((s,k), None)
keyring.set_keyring(MemKeyring())
FASTOPS_ENV = Path(tempfile.mkdtemp())/'.env'
test_eq(secret_set('_FO_TEST_KC', 'k'), {'keychain': True, 'file': None})
test_eq(FASTOPS_ENV.exists(), False)
test_eq(secret_set('_FO_TEST_TOKEN', 'tok123', save=True), {'keychain': True, 'file': str(FASTOPS_ENV)})
assert os.environ.get('_FO_TEST_TOKEN') == 'tok123'
assert secret_get('_FO_TEST_TOKEN') == 'tok123'
del os.environ['_FO_TEST_TOKEN']
assert secret_get('_FO_TEST_MISSING_XYZ', default='fallback') == 'fallback'

# A key the keychain does not hold, so the environment has to answer for it. `get_password`
# returns None rather than raising, so a falsy result must fall through, not return.
os.environ['_FO_TEST_ENV_ONLY'] = 'from-environ'
assert secret_get('_FO_TEST_ENV_ONLY') == 'from-environ'
del os.environ['_FO_TEST_ENV_ONLY']
print('secret_set/secret_get OK')
secret_set/secret_get OK

secrets reads several secrets at once and returns a dict of the keys that have a value. Missing keys are left out without a warning.


source

secrets

def secrets(
    *keys, service:str='fastops', path:NoneType=None
):

Return a dict of the given secrets that have a value, leaving out the missing ones.

secret_set('_FO_TEST_A', 'val_a', save=True)
secret_set('_FO_TEST_B', 'val_b', save=True)

result = secrets('_FO_TEST_A', '_FO_TEST_B', '_FO_TEST_MISSING')
assert result == {'_FO_TEST_A': 'val_a', '_FO_TEST_B': 'val_b'}
print('secrets() OK')
secrets() OK

Skill install

dockeasy includes a SKILL.md file that describes its API to coding agents. mv_skill_md copies it into .agents/skills/dockeasy/ and .claude/skills/dockeasy/, where agent tools such as Claude Code look for skills. The folders go under dir if you pass one, otherwise under the root of the current git repository, which repo_root finds, otherwise under the current folder. By default it only prints where it would copy the file; pass dry_run=False to copy it.


source

mv_skill_md

def mv_skill_md(
    dry_run:bool=True, dir:NoneType=None
)->None:

Copy the bundled SKILL.md into the agent skill folders under dir or the repository root; dry_run=True only prints the targets.


source

repo_root

def repo_root()->pathlib.Path:

Return the nearest folder at or above the current one that contains .git, or None.

import dockeasy.core
tmp = Path(tempfile.mkdtemp())
dockeasy.core.mv_skill_md(dry_run=True, dir=tmp)
dockeasy.core.mv_skill_md(dry_run=False, dir=tmp)
expected = (Path(dockeasy.core.__file__).parent/'SKILL.md').read_text()
assert (tmp/'.agents/skills/dockeasy/SKILL.md').read_text() == expected
assert (tmp/'.claude/skills/dockeasy/SKILL.md').read_text() == expected
print('mv_skill_md OK')
Would copy /home/runner/work/dockeasy/dockeasy/dockeasy/SKILL.md to: ['/tmp/tmp6bzf0opg/.agents/skills/dockeasy/SKILL.md', '/tmp/tmp6bzf0opg/.claude/skills/dockeasy/SKILL.md']
Installed -> ['/tmp/tmp6bzf0opg/.agents/skills/dockeasy/SKILL.md', '/tmp/tmp6bzf0opg/.claude/skills/dockeasy/SKILL.md']
mv_skill_md OK
import tomllib
deps = tomllib.loads((Path(dockeasy.core.__file__).parents[1]/'pyproject.toml').read_text())['project']['dependencies']
assert any(d.lower().startswith('pyyaml') for d in deps), 'core imports yaml, so pyyaml must be a dependency'

Regression checks

These checks use stand-ins for Docker and the keychain. Numeric flag values survive, build writes the Compose build section with the Dockerfile name it was given, drun keeps the protocol in a port key, and Compose.load keeps top-level keys such as secrets.

import unittest.mock as um
import subprocess
test_eq(mk_flags(short=False, retries=1, quiet=0, rm=True, pull=False), ['--retries=1', '--quiet=0', '--rm'])

built = {}
def fake_run(cmd, **kw):
    built.update(yaml.safe_load(Path(cmd[cmd.index('-f')+1]).read_text())['services']['img']['build'])
    return subprocess.CompletedProcess(cmd, 0, b'', b'')
d = tempfile.mkdtemp()
with um.patch('subprocess.run', fake_run): Dockerfile().from_('python').build(path=d, fn='Dockerfile.prod')
test_eq(built['dockerfile'], 'Dockerfile.prod')

sent = []
with um.patch.dict(globals(), _docker_cmd=lambda *a, **k: sent.append(a) or ''): drun('img', ports={'53/udp': 5353, 80: 8080})
test_eq([a for a in sent[0] if ':' in a], ['5353:53/udp', '8080:80'])

f = Path(d)/'dc.yml'
f.write_text('name: proj\nservices:\n  a: {image: x}\nsecrets:\n  s: {file: ./s.txt}\n')
list(Compose.load(f).to_dict())

The compose style is probed once, so later compose calls do not run docker-compose version again.

probes, styles = [], []
_compose_cmd.cache_clear()
with um.patch.dict(globals(), run=lambda *a, **k: probes.append(a) or ''):
    styles += [_compose_cmd(), _compose_cmd()]
_compose_cmd.cache_clear()
test_eq(len(probes), 1)
styles

With no keychain, secret_set writes the value to the .env file, sets its mode to 0600, issues a UserWarning that names the file, and returns the file in file. The fake below has no keychain, as on a Linux desktop with no Secret Service. The file exists first with mode 0644, so the test shows that secret_set tightens it. With the default save=False, the value does not go into os.environ.

env = Path(tempfile.mkdtemp())/'.env'
env.write_text(''); env.chmod(0o644)
with warnings.catch_warnings(record=True) as w, um.patch('keyring.core._keyring_backend', fail.Keyring()):
    warnings.simplefilter('always')
    test_eq(secret_set('_FO_TEST_NOKC', 'v', path=env), {'keychain': False, 'file': str(env)})
    test_eq(secret_get('_FO_TEST_NOKC', path=env), 'v')
test_eq([str(env) in str(x.message) for x in w], [True])
test_eq(env.stat().st_mode & 0o777, 0o600)
test_eq('_FO_TEST_NOKC' in os.environ, False)
str(w[0].message)

Export