Running OpenCode in Docker containers

Opencode is my daily driver for coding with LLMs, and I run it with permissions wide open: every edit allowed, every bash command allowed. On my host that would be reckless - one creative rm away from a bad afternoon - so the deal I made with myself is simple: the agent can do whatever it wants, but only inside a container. One container per project, nothing privileged, no docker socket, and the only thing it sees of my machine is the project directory. I still work in both modes - containerized and not - depending on the use-case; this post is about the containerized one.

My stack here is basically Rofi + Docker + OpenCode + tmux - rofi to pick a project, docker to keep the agent boxed, and tmux so I can jump inside the container and investigate at any time.

Why containers

A container is the only choice for true damage control. For one, an agent can work around any built-in permissions - especially if you use it for software development. You can try preventing rm -rf, but it still may land in a script, or as a failing application, or as a rogue npm run script - the agent can run those already, and it is allowed to edit the very file it is allowed to run. There are just too many gaps, no matter what the harness sandbox provides.

And when the agent itself goes sideways - say it reads a rogue prompt on a website or in some freshly cloned project - the permission list is negotiating with the wrong party. Inside a container you can limit it from wiping anything meaningful: the worst it can do is burn down the one directory it sees. You have remote backups, right? Right...?

The pieces

The whole setup fits in a handful of files - the image build context, a few host-side scripts, and config that gets mounted in:

opencode-docker/              # image build context
├── Dockerfile                # node + pinned opencode + tmux/git/rg/fd
├── opencode-wrapper          # opencode refuses to run outside tmux
├── entrypoint.sh             # detached tmux session, then sleep
├── oc                        # attach-or-create the session
└── tmux.conf                 # true-color passthrough for the TUI

~/.local/bin/
├── opencode-container        # start-or-reuse + attach, per project
├── opencode-container-name   # container name from a project path
└── opencode-container-state  # rofi annotator: ● running / ○ stopped

~/.config/rofi/scripts/
└── launcher.sh               # rofi script mode

~/.config/opencode/container/
└── opencode.json             # optional: your current config or a new one, mounted into containers

The image

The image is boring on purpose: node:26-slim, a pinned opencode-ai version, and the few tools the agent expects to find - git, ripgrep, fd, jq, tmux. A boring base is the deal - when a project needs more, you add the tools you see fit and rebuild. Two details matter. The opencode binary is replaced by a wrapper that refuses to run outside tmux, so the agent TUI always lives in a session I can detach from. And the entrypoint starts that session detached, then just sleeps - so the container outlives every terminal attached to it, and detaching never kills a run.

FROM node:26-slim

ARG OPENCODE_VERSION=1.18.29

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
      tmux git ripgrep fd-find jq less procps ca-certificates curl openssh-client \
 && rm -rf /var/lib/apt/lists/*

RUN npm install -g --no-update-notifier "opencode-ai@${OPENCODE_VERSION}" \
 && mv /usr/local/bin/opencode /usr/local/bin/opencode-real

COPY opencode-wrapper /usr/local/bin/opencode
COPY oc /usr/local/bin/oc
COPY entrypoint.sh /usr/local/bin/entrypoint
COPY tmux.conf /home/node/.tmux.conf
COPY opencode.json /home/node/.config/opencode/opencode.json

RUN chmod +x /usr/local/bin/opencode /usr/local/bin/oc /usr/local/bin/entrypoint \
 && mkdir -p /home/node/.local/share/opencode /project \
 && chown -R node:node /home/node /project

USER node

# UTF-8 locale so tmux renders multi-byte glyphs (box drawing, icons) correctly.
ENV LANG=C.UTF-8 \
    LC_ALL=C.UTF-8 \
    PROJECT_DIR=/project
WORKDIR /project

ENTRYPOINT ["/usr/local/bin/entrypoint"]

The wrapper, the entrypoint, the attach helper and the tmux config in full:

#!/bin/sh
# opencode must always run inside tmux so the session can be detached,
# reattached, and driven from the host. The real binary lives at
# /usr/local/bin/opencode-real and is only reachable through this wrapper.
if [ -z "${TMUX:-}" ]; then
  echo "opencode may only run inside tmux." >&2
  echo "Attach from the host with: docker exec -it <container> oc" >&2
  exit 1
fi
exec /usr/local/bin/opencode-real "$@"
#!/bin/sh
set -eu
: "${PROJECT_DIR:=/project}"
export PROJECT_DIR
cd "$PROJECT_DIR"

# Start the tmux server with an opencode session (detached).
if ! tmux has-session -t opencode 2>/dev/null; then
  tmux new-session -d -s opencode -c "$PROJECT_DIR" opencode
fi

# Container must stay alive independently of attached clients so that
# detaching never kills the session. Attach via: docker exec -it <ctr> oc
exec sleep infinity
#!/bin/sh
# Attach to the opencode tmux session, creating it if it died.
# Runs INSIDE the container; on the host use: docker exec -it <container> oc
exec tmux new-session -A -s opencode -c "${PROJECT_DIR:-/project}" opencode
set -g mouse on
set -g history-limit 100000
set -g default-terminal "tmux-256color"

# Pass 24-bit color and styled underlines through to the inner TUI.
# Required because docker exec does not forward the real terminal's
# capabilities, so tmux would otherwise downgrade to 256 colors.
set -as terminal-features ',*:RGB:24'
set -as terminal-overrides ',*:RGB'
set -as terminal-overrides ',*:Smulx=\E[4::%p1%dm'
set -as terminal-overrides ',*:Setulc=\E[58::2::%p1%{16384}%+%d::%p2%{256}%+%d::%p3%;'

set -g status-left "#[bold]#[fg=colour4] opencode-agent #[fg=colour8]| "
set -g status-right "#S #h:%p "

The baked-in opencode config allows everything: edit, bash. The one thing I hold back is internet access - webfetch is a straight channel for leaking your project data to somewhere you did not intend. When the project holds nothing confidential anyway, you can basically give the model a free hand without risk. That is the point of the container: instead of teaching the agent manners, the blast radius stays small - the permission boundary moves from prompts to the container boundary.

{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "allow",
    "bash": {
      "*": "allow"
    },
    "external_directory": {
      "*": "allow"
    }
  }
}

The launcher

On the desktop everything starts from rofi. One script serves a few modes - plain opencode, the containerized one, zeditor - and lists project directories from a couple of roots. Here it is in full:

#!/bin/bash

LAUNCHER="${1:-}"
shift

PROJECTS=(
	~/projects
	~/work
	~/sideprojects
)

# COMMAND runs on selection; ANNOTATOR (optional) decorates the list and may
# pass clean payloads via rofi `info` (read from $ROFI_INFO on selection).
case "$LAUNCHER" in
	opencode) COMMAND=(alacritty -e opencode) ;;
	occ)      COMMAND=("$HOME/.local/bin/opencode-container") ANNOTATOR="$HOME/.local/bin/opencode-container-state" ;;
	zed)      COMMAND=(zeditor -n) ;;
	*)        echo "unknown launcher: $LAUNCHER" >&2; exit 1 ;;
esac

list_all() {
	for project in "${PROJECTS[@]}"; do
		find "$project" -maxdepth 1 -type d | tail -n +2
	done
}

if [[ -z "$@" ]]; then
	if [[ -n "${ANNOTATOR:-}" && -x "$ANNOTATOR" ]]; then
		list_all | "$ANNOTATOR"
	else
		list_all
	fi
else
	# rofi script mode: ROFI_RETV=1 entry selected, 10+ = custom hot key
	# (kb-custom-1 = Alt+s -> stop). Entries with `info` deliver their clean
	# payload via ROFI_INFO; fall back to the raw selection otherwise.
	RETV="${ROFI_RETV:-1}"
	SELECTION="${ROFI_INFO:-$*}"

	case "$RETV" in
		10) # Ctrl+s: stop the selected project's container
			ctr="$("$HOME/.local/bin/opencode-container-name" "$SELECTION")"
			docker stop "$ctr" >/dev/null || true
			;;
		11) # Ctrl+r: remove the container (force) along with its session
			ctr="$("$HOME/.local/bin/opencode-container-name" "$SELECTION")"
			docker rm -f "$ctr" >/dev/null || true
			;;
		*)
			coproc ("${COMMAND[@]}" "$SELECTION" & >& /dev/null) &
			;;
	esac
fi

The interesting mode is occ: the plain directory list is piped through an annotator (opencode-container-state) which decorates each entry with the container state - ● running, ○ stopped, no marker when there is no container yet - and hands rofi the clean path as an info payload, so the markers never leak into paths. Enter launches or reattaches, Ctrl+s stops the selected project's container, Ctrl+r removes it entirely. The annotator just reads docker ps -a filtered by name prefix; no state files, nothing to get out of sync.

rofi menu listing project directories, running containers marked ●, stopped ones ○
#!/usr/bin/env bash
# Generic rofi annotator for the occ mode: reads candidate project dirs on
# stdin, prints them with the opencode container state as a prefix:
#   ● <dir>  running   ○ <dir>  stopped   <dir>  no container yet
# Entries carry rofi `info` payloads (clean path) for the launcher. Stopping
# a container is done via the rofi hot key (Alt+s, kb-custom-1) -> the
# launcher sees ROFI_RETV=10; no stop entries are listed.
set -eo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"

printf '\0use-hot-keys\x1ftrue\n'
printf '\0message\x1f  Ctrl+s stop   ·   Ctrl+r remove   ·   Enter attach/open\n'

declare -A STATE
while read -r cname state; do
	STATE["$cname"]="$state"
done < <(docker ps -a --filter 'name=^opencode-' --format '{{.Names}} {{.State}}' || true)

declare -a RUN STOPPED NONE
while IFS= read -r dir; do
	ctr="$("$SCRIPT_DIR/opencode-container-name" "$dir" 2>/dev/null)" || { NONE+=("$dir"); continue; }
	case "${STATE[$ctr]:-}" in
		running)                    RUN+=("$dir") ;;
		exited|created|paused|dead) STOPPED+=("$dir") ;;
		*)                          NONE+=("$dir") ;;
	esac
done

emit() { printf '%s\0info\x1f%s\n' "$1" "$2"; }

for dir in "${RUN[@]:-}"; do [[ -n "$dir" ]] && emit "● $dir" "$dir"; done
for dir in "${STOPPED[@]:-}"; do [[ -n "$dir" ]] && emit "○ $dir" "$dir"; done
for dir in "${NONE[@]:-}"; do [[ -n "$dir" ]] && emit "$dir" "$dir"; done

A tiny helper (opencode-container-name) derives the container name from the project path - opencode-<name>-<hash>, six hash characters - and is shared by the launcher, the annotator, the fish helpers and the start script. One source of truth, so nothing disagrees about which container belongs to which project, and the hash keeps same-basename projects apart.

#!/usr/bin/env bash
# Print the opencode-agent container name for a project dir.
# Single source of truth: used by opencode-container, the rofi occ mode,
# and the fish helpers.
set -euo pipefail

PROJECT="$(readlink -f "${1:?usage: opencode-container-name <project-dir>}")"
NAME="$(basename "$PROJECT")"
NAME="${NAME//[^a-zA-Z0-9_.-]/-}" # docker name charset
HASH="$(printf '%s' "$PROJECT" | sha1sum | cut -c1-6)"
echo "opencode-${NAME}-${HASH}"

opencode-container

The launcher calls one script with the project path; the same script works fine from a terminal. This is the whole machinery:

#!/usr/bin/env bash
# Start (or reuse) the opencode-agent container for a project and attach.
# Used by the rofi 'occ' mode; also usable from a terminal:
#   opencode-container <project-dir>   (rofi may pass a ● / ○ marked entry)
# ATTACH_TERM can override the terminal used for attaching (default: alacritty).
set -euo pipefail

SEL="${1:?usage: opencode-container <project-dir>}"
SEL="${SEL#● }" # strip rofi state markers
SEL="${SEL#○ }"
PROJECT="$(readlink -f "$SEL")"
CTR="$("$(dirname "$(readlink -f "$0")")/opencode-container-name" "$PROJECT")"
IMAGE="opencode-agent:1.18.29"
DATA_VOL="opencode-agent_oc-data"

# Single source of truth for LLM credentials: the host's auth.json is
# bind-mounted (rw) so logins/token refreshes propagate both ways.
AUTH_SRC="$HOME/.local/share/opencode/auth.json"
AUTH_MOUNT=()
[[ -f "$AUTH_SRC" ]] && AUTH_MOUNT=(-v "$AUTH_SRC:/home/node/.local/share/opencode/auth.json")

# Provider config (llama-swap, fireworks-personal, ...) lives on the host so
# secrets stay out of the image; overrides the baked-in config when present.
CFG_SRC="$HOME/.config/opencode/container/opencode.json"
CFG_MOUNT=()
[[ -f "$CFG_SRC" ]] && CFG_MOUNT=(-v "$CFG_SRC:/home/node/.config/opencode/opencode.json")

docker image inspect "$IMAGE" >/dev/null 2>&1 ||
  docker build -t "$IMAGE" "$(dirname "$(readlink -f "$0")")" >/dev/null

if docker container inspect "$CTR" >/dev/null 2>&1; then
  docker start "$CTR" >/dev/null # no-op when already running
else
  # Workdir is named after the project instead of a generic /project.
  NAME="$(basename "$PROJECT")"
  NAME="${NAME//[^a-zA-Z0-9_.-]/-}" # path-safe
  case "$NAME" in                   # avoid clobbering image paths
    usr|etc|home|root|tmp|var|opt|srv|bin|sbin|lib|lib64|lib32|project) TARGET=/project ;;
    *) TARGET="/$NAME" ;;
  esac
  docker run -d --name "$CTR" \
    --restart unless-stopped \
    -v "$PROJECT:$TARGET" \
    -e "PROJECT_DIR=$TARGET" \
    -v "$DATA_VOL:/home/node/.local/share/opencode" \
    ${AUTH_MOUNT[@]+"${AUTH_MOUNT[@]}"} \
    ${CFG_MOUNT[@]+"${CFG_MOUNT[@]}"} \
    "$IMAGE" >/dev/null
fi

exec "${ATTACH_TERM:-alacritty}" -e docker exec -it "$CTR" /usr/local/bin/oc

What happens on launch: strip the rofi state markers, resolve symlinks, compute the container name. If the pinned image is missing it gets built. An existing container is just started - a no-op when it already runs - otherwise docker run creates it with the project bind-mounted at /<project-name>, not a generic /project, because prompts, tmux status bars and tab completion all read nicer with the real name. Names that could collide with image paths (imagine a project literally called usr) fall back to /project.

The mounts are where the design lives. The project comes in as-is, git included - more on that in a second. A shared named volume holds all opencode state: session transcripts and auth. Transcripts survive docker rm, which is what makes Ctrl+r safe to press. The host's auth.json is bind-mounted read-write on top: log in once on the host and every container sees the credentials, and token refreshes flow back the other way too. Provider config (custom providers, local proxies) is mounted from the host as well. And --restart unless-stopped brings everything back after a reboot.

Finally the script opens a terminal attached to the container's tmux session - oc inside the container is just tmux new-session -A -s opencode. Pick another project in rofi and you get another independent container; come back later and the run is still there, detached, churning along. The fish helpers covered in the bonus section at the end do the same from a terminal.

Passing through git

The bind mount includes .git, deliberately. But it also could deliberately mount .git as tmpfs or another volume. The agent gets a real repo context - it sees the branch, the log, the diff - and can just commit its work like any other collaborator with a shell. The flip side: nothing separates it from your local history either. An over-eager rebase or a destructive cleanup is within its reach, including the commits you had there before it showed up. So the rule is to commit or push before letting the agent loose on a project that matters, and keep a bare mirror somewhere outside the container's reach for the paranoid cases.

It works, but this is the weakest joint of the setup, and it deserves better than rules of thumb. That is what the next posts will look at: the different strategies for separating the agent from your local git copy.

Bonus: fish helpers

Rofi is the main entrance, but if you live in a terminal, three fish functions give the same per-project control from inside a project directory: oc attaches to the container, ocshell opens an extra shell window in the tmux, and ocstop stops the container. Drop the file into ~/.config/fish/functions/ and they are always at hand:

# Host-side fish helpers for opencode-agent containers (one per project).
# Container name: opencode-<project>-<hash-of-real-path> — must stay in
# sync with ~/.local/bin/opencode-container.

function __occ_ctr --description "opencode container name for a dir (default: PWD)"
    set -l dir $argv[1]
    test -z "$dir"; and set dir $PWD
    set -l resolved (realpath "$dir" 2>/dev/null); or set resolved "$dir"
    set -l name (basename "$resolved")
    set name (string replace -ra '[^a-zA-Z0-9_.-]' '-' -- "$name")
    set -l hash (printf '%s' "$resolved" | sha1sum | string sub -l 6)
    echo "opencode-$name-$hash"
end

function oc --description "Attach to the opencode container for the current project (or given dir)"
    docker exec -it (__occ_ctr $argv[1]) /usr/local/bin/oc
end

function ocshell --description "Open a shell window in the opencode tmux of the current project"
    docker exec -it (__occ_ctr) tmux new-window -t opencode -a sh
end

function ocstop --description "Stop the opencode container for the current project (or given dir)"
    docker stop (__occ_ctr $argv[1])
end