Skip to content

About

Image and script for seamlessly running Claude Code / Codex / Vibe / Gemini CLI in a Docker or Apple Container.

Resources

Stars

25 stars

Watchers

1 watching

Forks

Repository files navigation

AI Contained

Warning

Breaking change (September 2026): Codex state is now isolated per folder. Sharing the native ~/.codex with containers could silently lose Codex history, because file locks do not work across the container filesystem boundary. Contained Codex now gets its own persistent history per working folder, and a folder can only be used by one container at a time. Rebuild the image and remove old aic- containers before using the updated launchers. Existing native history is preserved but is not imported. See Why Codex state is isolated for what changed and how it differs between tools and runtimes.

Seamlessly run CLI coding agents (Claude, Codex, Gemini, Vibe) inside an Apple Container or Docker container with persistent state.

The main goal is to provide a seamless experience; alias claude='claude-contained --yolo' and now claude runs in a container with your settings. Only . or the folders you specify are shared with the container. History is retained (even if you switch back to un-contained claude).

There are some caveats:

  • Host localhost access: -H PORT works with claude-docked (Docker) but not claude-contained (Apple Containers) for services bound to localhost. See Accessing Host Services. (Apple Containers seems to be gaining support soon.)
  • ~/.claude.json is relocated: On first run, your ~/.claude.json is moved to ~/.claude-contained/shared/.claude.json and replaced with a symlink. This allows containers to share the file. If you delete ~/.claude-contained/, you will lose your Claude credentials and some settings. You'll have to log in again. This is a limitation on how files can be shared with the container.
  • Don't mix contained and uncontained at the same time: Running claude-contained and regular claude simultaneously may cause issues, as both access the same config file but through different paths. Run one or the other, not both at once. This will be fixed in the future.
  • Codex and PATH: Codex runs commands via bash -lc, which sources /etc/profile and resets PATH to the Debian default. This means tools installed outside standard locations (e.g., via SDKMAN) won't be found unless symlinked into /usr/local/bin/. The image includes symlinks for java, javac, jar, mvn, and jbang. If you install additional tools in non-standard paths, add similar symlinks in the Dockerfile.

Quick Start

Apple Containers (macOS)

  1. Build the container:

    container build --platform linux/arm64 -t claude-contained .
  2. Put claude-contained somewhere on your PATH, optionally aliasing to claude.

    alias claude='claude-contained --yolo'
    alias vibe='claude-contained -t vibe --yolo'
    alias codex='claude-contained -t codex --yolo'
    alias gemini='claude-contained -t gemini --yolo'
    
  3. Run:

    claude-contained              # Current directory
    claude-contained ./my-project # Specific directory

Docker

  1. Build the container:

    docker build --platform linux/arm64 -t claude-contained .
  2. Put claude-docked somewhere on your PATH.

  3. Run:

    claude-docked              # Current directory
    claude-docked ./my-project # Specific directory

Usage

claude-contained [options] [main_dir] [extra_dir ...] [-- <tool args...>]

Options

Flag Description
-t, --tool TOOL AI tool to run: claude (default), codex, gemini, vibe
-R, --rebuild[=MODE] Rebuild image before run: tools (default) or full
-H PORT[:HOSTPORT] Forward host port to container localhost (can be repeated)
-p HOST:CONTAINER Publish container port to host (can be repeated)
-s, --shell Start a bash shell instead of the AI tool (for debugging)
-S, --ssh Enable SSH agent forwarding (for git push)
-w, --worktree Auto-include git worktree's main repository (skip prompt)
-y, --yolo Skip all permission prompts (tool-specific flag)
-N, --contained-node-modules Use container-specific node_modules (skip prompt)
--share-skills=DIR Share skill folders from DIR (repeatable, opt-in; accepts ~/)
-a, --attach [NAME] Attach to running container (runs tool, or bash with -s)
-h, --help Show help message

Supported Tools

Tool Command Yolo Flag Config Dir
Claude Code claude --dangerously-skip-permissions ~/.claude
OpenAI Codex codex --yolo ~/.codex
Google Gemini CLI gemini --yolo ~/.gemini
Mistral Vibe vibe --auto-approve ~/.vibe

Config directories are mounted regardless of which tool you run. Codex’s in-container ~/.codex comes from the selected folder’s private store, never native ~/.codex.

Behavior

  • First directory is the working directory
  • Additional directories are mounted and auto-added via --add-dir (Claude and Codex only)
  • Append :ro to an extra dir to mount it read-only (or :rw to force read-write); use --readonly-extras to default all extras to read-only
  • Tool configs and Maven cache (~/.m2) are bind-mounted for persistence
  • Repeat --share-skills=DIR to combine shared skills; the first source receives new skills.
  • SSH agent forwarding is disabled by default; use -S/--ssh to enable
  • The GitHub CLI is included, with the gh-stack extension preinstalled (gh stack ...). Extensions are baked into the image under /opt/gh and linked into ~/.local/share/gh/extensions at startup; add more with the GH_EXTENSIONS build arg (space-separated, e.g. container build --build-arg GH_EXTENSIONS="github/gh-stack owner/gh-foo" -t claude-contained .)
  • The Rust toolchain ships with clippy, rustfmt, just, the cargo nextest test runner, plus the lint/format helpers typos, taplo, and cargo dylint (with dylint-link). Versions can be pinned with the TYPOS_VERSION, TAPLO_VERSION, NEXTEST_VERSION, and DYLINT_VERSION build args.
  • Rust state is persisted in container-specific directories — ~/.claude-contained/cargo-linux-<arch> is mounted as ~/.cargo and ~/.claude-contained/rustup-linux-<arch> as ~/.rustup — so crates, extra toolchains (rust-toolchain.toml pins, dylint's nightly) and dylint drivers survive across runs. Your host ~/.cargo/~/.rustup are left alone: they hold macOS binaries that cannot run in the Linux container, and rustup rewrites the proxies in ~/.cargo/bin whenever it installs a toolchain. The image's stable toolchain is symlinked into the mount rather than copied, so only newly installed toolchains use space there.
  • Java hot reload is left to the Vaadin Dev Loop (mvn vaadin:install-dev-cli, then .vaadin/vaadin-dev). The image provides the JetBrains Runtime it prefers (/opt/jbr, found via JAVA_HOME) but sets no global JAVA_TOOL_OPTIONS and bundles no HotswapAgent: the Dev Loop provisions its own agent in ~/.vaadin/devloop, and a second, globally loaded one double-instruments the app. Outside the Dev Loop, pass hotswap flags in your own run configuration.
  • ~/.vaadin is shared with the host, except ~/.vaadin/jdk, which is replaced by ~/.claude-contained/vaadin-jdk-linux-<arch>. The Vaadin IDE plugins install macOS JetBrains Runtimes there, and the Dev Loop would otherwise pick one (for a Java 21 project) that cannot run in the container.
  • Official Google Chrome stable is installed at /opt/google/chrome (Linux arm64 included), which is the browser @playwright/mcp and Playwright's chrome channel use, so the MCP works with any Playwright version and never downloads a browser. Browsers a project's own Playwright installs go to /ms-playwright, persisted in ~/.claude-contained/ms-playwright-linux-<arch> and shared by all projects, so each revision downloads once. Selenium/TestBench use Debian's chromium + chromedriver.
  • Git worktrees are detected; main repository is included for full git access
  • If a mounted main repository has linked worktrees outside the mounted directories, the launcher offers to auto-lock those worktrees while the container runs (otherwise an in-container git worktree prune/git gc could remove them). Auto-lock reasons use cc-autolocked-by: and are removed when the last owning container exits. The locking is self-healing — a lock left behind by a launcher that was killed is reclaimed automatically by the next run — and fail-safe, applying the locks even if the internal mutex is unavailable so the container never runs with worktrees unprotected.

Why Codex state is isolated

Codex keeps its history in SQLite. Both Apple Containers and Docker Desktop expose host folders through virtiofs, and a file lock taken on one side of that boundary is invisible on the other. Two writers, whether host plus container or two containers, both believe they hold the lock, both commit, and half of the acknowledged rows vanish while SQLite's integrity check still reports ok. This was reproduced with a synthetic database and no Codex involved; see investigations/codex-history. Sharing the native ~/.codex with any container was therefore never safe, and no in-container locking can fix it. The fix removes the shared database and guarantees that only one container ever mounts any Codex store.

How it works:

  • Private Codex home per folder. Native ~/.codex is no longer mounted. Each working folder gets its own persistent home under ~/.claude-contained/codex/projects/, seeded once with setup files but never with databases or transcripts.
  • A host-side supervisor owns the folder. Before anything runs, an embedded Python script takes a native flock on the Mac's own filesystem, where locks work, and records the owning container's name, runtime, and a random token that is also stamped on the container as a label. The lock descriptor is inherited by the launcher, so a killed supervisor cannot release ownership early, and lock files are never deleted. If the runtime cannot be queried, ownership is kept rather than guessed.
  • Attach instead of a second container. Launching any tool for an owned folder shows the owning container and its shared folders, asks for confirmation, and runs the tool inside that container.
  • A guard replaces codex in the image. It refuses to run without the root-owned identity written by the entrypoint, pins the Codex home and database to the private store, forces file-based credentials, and blocks --cd, background daemons, and config overrides that would relocate the database. Running Codex by hand from a debug shell goes through the same guard.
  • Claude's shared config moved. Only ~/.claude-contained/shared is mounted, so containers no longer see the directory that holds every Codex store.

How behavior differs:

Situation Behavior
Claude, Copilot, Gemini, Vibe Config directories are shared as before. A second launch for the same folder offers to attach to the owning container instead of starting another.
Codex Private per-folder history, guard-enforced home, no native state shared.
Apple Containers Several Codex sessions may run at once inside the owning container; they share one Linux kernel, so Codex's own same-conversation check works.
Docker One Codex process per folder, enforced by a container-local lock. Other tools can still attach.
Mixed runtimes A folder owned by a Docker container cannot be attached from Apple Containers or the reverse.
Old containers Launchers refuse to run while any unlabeled aic- container exists. Rebuild the image and remove them first.

Unchanged: path parity, UID matching, worktree locking, shared skills, the node_modules overlay, and single-file launcher installs. Different folders still run fully in parallel. The details follow.

Codex history and container reuse

Both launchers require Python 3.9+ on the host. Each canonical primary folder gets its own durable Codex home under ~/.claude-contained/codex/projects/<folder>-<path-hash>/home. Relative paths, symlinks, and macOS case aliases select the same store; separate worktrees select different stores. Additional mounted folders do not change history ownership. Pass the working folder to the launcher, rather than forwarding Codex --cd/-C. Moving a folder selects a new store; there is no automatic relocation or merge.

On first use, config.toml, AGENTS.md, skills, and plugins are copied into the private home if present. Databases and transcripts are not copied. Subsequent setup changes stay private to that folder.

Codex credentials are shared across contained projects in ~/.claude-contained/codex/auth/auth.json. Only this small auth directory is mounted alongside each private home, whose auth.json links to the shared file. The shared cache is seeded once from native ~/.codex/auth.json, or from the first migrated project's private credential if no native file exists. Native credentials are otherwise independent. If credentials exist only in the macOS keychain, sign in once inside contained Codex. Signing in in one project then covers all contained projects. Existing private auth files are retained as auth.json.before-sharing-* backups; they contain secrets. An empty shared cache after logout is never reseeded.

This is a pragmatic concurrency tradeoff: simultaneous refreshes or reads during a JSON rewrite can still fail and require signing in again. History remains isolated. codex logout clears the shared cache for all contained projects; a TUI logout/relogin is reconciled when that Codex process exits normally. Prefer CLI logout after closing other sessions. Rebuild the image and restart containers when upgrading to shared auth. File credentials are forced, and database-location overrides and external state symlinks (except the exact auth link) are refused. Native CLI/Desktop can keep using native history independently. This does not repair previously damaged history; preserve an offline backup before recovery.

A host lock reserves each folder for one container across both runtimes. Different folders can run concurrently. Starting any agent for an occupied folder offers to start it in the existing container, with explicit confirmation, including with --yolo. Decline or EOF cancels. The requested tool, arguments, and working folder are preserved. The confirmation lists the folders the owning container shares, and the attached agent gets all of them; a folder or access mode the owner does not already share is refused. The other setup options (shared skills, ports, SSH, worktree/node options, memory, image, and GitHub token) must match the original; incompatible options are refused rather than ignored. Use the owning runtime for mixed-runtime attachment.

  • Apple Containers: independent Codex sessions can run concurrently in the owning container. Codex prevents simultaneous writing to the same conversation.
  • Docker: only one Codex process per folder may run at a time. A container-local lock enforces this for ordinary starts, attachment, and Codex invoked from a debug shell. Other agents may still reuse that container.
  • Lifecycle: attachment shares the original container’s filesystem and lifetime; attached agents can end when its original session exits. A surviving orphan retains ownership. A stopped container must be removed before its store can be reused elsewhere. Unknown runtime state never authorizes a second mount.

Only managed launcher/guard entry points are supported. Old containers, direct Codex binaries bypassing the guard, background app-server daemons, and devcontainer Codex starts are unsupported. Do not open private contained stores with native Codex. Mounting HOME or the native/private state directories as project or skills sources is refused. Other agents’ state remains shared as before. Claude’s shared config moves into ~/.claude-contained/shared/, with its old path retained as a symlink, so containers need not see the directory containing all Codex stores.

The launcher remains installable as one file. Maintainers edit managed-launch.py and run python3 tests/embed-managed-launch.py to update both embedded copies. CLAUDE_CONTAINED_IMAGE optionally selects an image (default claude-contained:latest); the image must include the guarded entrypoint.

Shared Skills

claude-contained and claude-docked support the same repeatable --share-skills=DIR option. Put the directory that should receive new skills first:

claude-contained --share-skills=~/Projects/skills --share-skills=~/Projects/skills-public .
claude-docked --share-skills=~/Projects/skills --share-skills=~/Projects/skills-public .

Both commands combine the sources at ~/.claude/skills, ~/.codex/skills, ~/.agents/skills, ~/.copilot/skills, ~/.gemini/skills, and ~/.vibe/skills inside the container. Sharing is opt-in, with no default source. Paths may be absolute, relative, or start with ~/.

  • New skills: Creating a skill under any shared target writes it directly into the first source (~/Projects/skills above).
  • Existing skills: Edits write back to the source that contains the skill. For example, editing a skill from skills-public updates that repository.
  • Combined contents: The first source is mounted as the shared root. Non-hidden, nonempty top-level directories from later sources are mounted beneath it. Hidden entries, empty directories, and root files from later sources are excluded.
  • Conflicts: Duplicate names cause an error, except that an empty directory in the first source can serve as a mountpoint. Files, symlinks, and nonempty directories in the first source are never hidden by a later source.
  • Host folders: Empty mountpoint directories may appear in the first source on the host. Git does not track them, and no skill data is copied there.
  • Codex built-ins: The private Codex home’s skills/.system remains mounted at the Codex target. It is initially copied with the other skills.

Startup lists the sources and container targets in one line, marking where new skills go:

Skills: [~/Projects/skills (new skills here), ~/Projects/skills-public] -> [~/.claude/skills, ~/.codex/skills, ~/.agents/skills, ~/.copilot/skills, ~/.gemini/skills, ~/.vibe/skills]

Start a new container after changing the source list or adding or moving skill directories in later sources. No image rebuild is needed for this launcher feature.

Examples

# Tool selection
claude-contained                                    # Claude (default)
claude-contained -t codex .                         # OpenAI Codex
claude-contained -t gemini .                        # Google Gemini CLI
claude-contained -t vibe .                          # Mistral Vibe

# Common usage
claude-contained . ../other/project                 # Multiple directories
claude-contained . ../lib:ro                        # Mount ../lib read-only
claude-contained --readonly-extras . ../a ../b      # All extras read-only
claude-contained . -- --model sonnet --verbose      # Pass args to tool
claude-contained -y -t codex .                      # Codex with --yolo
claude-contained --rebuild .                        # Refresh AI tools first
claude-contained --rebuild=full .                   # Full fresh rebuild first
claude-contained -s                                 # Debug shell
claude-contained --share-skills=~/Projects/skills . # Share skills into tool skill dirs

# Port forwarding
claude-contained -p 8080:8080 .                     # Expose port 8080
claude-contained -H 3845 .                          # Forward host:3845 to container

Rebuilding the Image

Use the launcher when you want the image refreshed before starting a new session:

claude-contained --rebuild .      # Refresh AI CLI layers
claude-contained --rebuild=full . # Full fresh rebuild (--pull --no-cache)
claude-docked --rebuild .
claude-docked --rebuild=full .

tools rebuilds the AI CLI portion of the image and everything after it, which updates Claude Code, Codex, Gemini, Vibe, and Copilot without invalidating the entire build. If that targeted rebuild fails, the launcher automatically retries with a full rebuild.

full forces a clean rebuild of the entire image and pulls the latest base image. Rebuild requires the launcher script to run from this repo checkout, or via a symlink into it, so it can find the local Dockerfile.

Rebuilds stamp the image with a hash of the files it is built from (Dockerfile, entrypoint.sh, install-rust-tools.sh, codex-guard.py, and custom-packages.txt if present), stored as the io.claude-contained.source label. After a successful build the launcher checks that claude-contained:latest, the name it runs, carries the new hash. Apple's container has been seen keeping an older image under the same short name, so every rebuild went to docker.io/library/claude-contained:latest while launches still ran the old copy. If that happens, the rebuild fails with the command to remove the stale copy (container image delete claude-contained:latest, then rebuild). Every launch also compares the label with the checkout and warns, without blocking, when the image was built from other sources, for example after a git pull without a rebuild. Images without the label (built before this check, or with a plain container build) get a one-line note; a CLAUDE_CONTAINED_IMAGE override is not checked.

Apple Container rebuilds use a temporary Dockerfile with ordinary leading # comments removed to avoid its build-request size limit. Parser directives, shebangs, and everything from the first heredoc onward are preserved. The original Dockerfile and build context stay intact; Docker builds do not need this workaround.

The launcher reports the original and trimmed byte counts and warns if the trimmed file is still 14 KiB or larger. This is advisory headroom below the reported ~16 KiB limit, not a guaranteed cutoff: request overhead varies. If a build immediately fails with Stream unexpectedly closed or Transport became inactive, try moving inline scripts into separate COPYed files or shortening the Dockerfile further. These errors can also have other causes. Both launchers retain the same rebuild modes; only Apple Container needs trimming and this warning.

Node.js Projects (node_modules Overlay)

When running on macOS, the container is Linux — but node_modules often contains platform-specific native binaries (e.g., esbuild, swc, sharp) that are compiled for the host architecture. macOS arm64 binaries won't work inside a Linux aarch64 container, even though the CPU architecture is the same, because the OS ABI differs.

To handle this, the scripts automatically detect Node.js projects (directories with a package.json) and offer to create a container-specific node_modules directory:

Node.js project detected. Use container-specific node_modules? [Y/n]

If accepted, a .claude-contained/node_modules-linux-aarch64/ directory (or node_modules-linux-x86_64 on Intel Macs) is created inside your project and mounted over node_modules inside the container. You should add .claude-contained/ to your .gitignore manually (this also tells IDEs like IntelliJ and VS Code to skip indexing it). This keeps host and container dependencies separate — each platform gets the correct native binaries.

First run

After accepting the prompt, run your package manager inside the container to install Linux-native dependencies:

npm install    # or yarn, pnpm, bun, etc.

Subsequent runs

The overlay directory persists on the host, so dependencies survive across container sessions. No re-install needed unless you change package.json.

Skipping the prompt

Use -N (or --contained-node-modules) to auto-accept without prompting:

claude-contained -N .

.gitignore

You should manually add .claude-contained/ to your project's .gitignore to exclude overlay directories from version control.

When it's skipped

  • Linux hosts: No overlay needed — host and container share the same OS, so native binaries are already compatible.
  • No package.json: No prompt, no overlay.

Accessing Host Services

The container runs in an isolated network, so localhost refers to the container itself, not your Mac. To connect to services running on your Mac, use host.local or the -H flag.

Docker (claude-docked) - Recommended for Host Services

Use -H PORT to forward host ports to container localhost. This works because Docker Desktop has special routing to reach services bound to 127.0.0.1 on the host.

claude-docked -H 3845 .           # Forward host:3845 to container localhost:3845
claude-docked -H 3845 -H 8080 .   # Multiple ports

Apple Containers (claude-contained) - Limited Host Access

Apple Containers can only reach host services bound to 0.0.0.0 (all interfaces), not 127.0.0.1 (localhost only). Most services (including Figma Desktop) bind to localhost only for security. See apple/container#346 for the feature request to add host.docker.internal equivalent.

What works:

  • Services you control that bind to 0.0.0.0
  • Using host.local hostname for services on all interfaces

What doesn't work:

  • -H flag for localhost-bound services (like Figma Desktop MCP)

For localhost-bound services, use claude-docked instead.

Configuring Figma Desktop MCP

Figma Desktop MCP binds to localhost:3845. Use Docker:

claude-docked -H 3845 .

Requirements:

  • Figma Desktop must be running on your Mac
  • The Figma MCP server must be enabled (Figma Desktop → Settings → enable MCP)
  • Port 3845 is the default; adjust if you've changed it

Other MCPs

For MCPs that expect localhost, use claude-docked -H PORT.

For services bound to all interfaces (0.0.0.0), you can use host.local in a .mcp.json override:

{
  "mcpServers": {
    "my-mcp": {
      "type": "http",
      "url": "http://host.local:PORT/mcp"
    }
  }
}

VS Code Devcontainer

Use the claude-contained image as a VS Code devcontainer for Java/Spring/Vaadin development with full IDE features and Claude in the terminal.

What It Provides

  • Full Java IntelliSense, debugging, and Spring Boot support via pre-installed extensions
  • claude command available in the integrated terminal
  • Path parity: Your project stays at its original path (not /workspaces/project)
  • Maven cache and git config shared with host

Setup

  1. Build the Docker image first:

    docker build -t claude-contained .
  2. Copy the template to your project:

    cp -r devcontainer/ /path/to/your-project/.devcontainer/
  3. Open the project in VS Code and select "Reopen in Container"

Included Extensions

  • Red Hat Java (IntelliSense)
  • Debugger for Java
  • Test Runner for Java
  • Maven for Java
  • Spring Boot Extension Pack
  • Lombok Annotations Support
  • GitLens

Limitations

  • Image must be pre-built: Run docker build before using
  • Don't run simultaneously: Avoid running devcontainer while also using standalone claude-contained or claude-docked (shared ~/.claude state)
  • host.local may not work: VS Code manages networking differently; use explicit port forwarding instead

See devcontainer/README.md for detailed usage and customization options.

About

Image and script for seamlessly running Claude Code / Codex / Vibe / Gemini CLI in a Docker or Apple Container.

Resources

Stars

25 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages