Published on
Last updated on
Last updated on

Coding agents in secured VS Code dev containers

Hero image
Authors
  • avatar
    Name
    Daniel Demmel
    Occupation
    Software engineer with
    21 years of professional
    experience

2026-11-01 update: I don't really recommend this setup as a security boundary any more. The comments below (thank you all!) and a few more months of poking at it convinced me that a single container layer doesn't cut it any more. Docker Desktop's default VM mounts the whole of /Users and runs a rootful engine, so a container escape lands somewhere with your SSH keys in reach. And VS Code keeps creating fresh IPC sockets into the container – one per terminal – which turns hardening into a race you can only ever mostly win.

So I ended up building Foldyard instead: a throwaway VM per project that mounts only the repo, runs the whole dev stack on rootless Podman, and keeps credentials on your computer behind a proxy. That said, if a dev container is what you can set up today, it's still a lot better than running an agent straight on your laptop – the rest of this post is a reasonable way to do it, just don't mistake it for a proper wall.


Why do we need sandboxed agents

Simon Willison describes the lethal trifecta as the combination of:

  1. Access to an LLM – the agent can generate arbitrary code and commands
  2. The ability to execute code – the agent can run what it generates
  3. Access to untrusted content – web pages, npm packages, user files that could contain prompt injections

When all three are present, you've got a recipe for trouble. A malicious npm package or a cleverly crafted webpage could inject prompts that convince the agent to execute harmful commands. Even without malicious intent, the agent could make mistakes with destructive consequences.

The goal isn't to eliminate risk entirely – it's to limit the blast radius. If something goes wrong, we want it contained to the sandbox rather than having full access to your machine, credentials, and the ability to push malicious code to your repositories.

The future might be cloud, but it's not here yet

Claude Code Web is useful for exploration, but it's not empowered and flexible enough to run specific test harnesses that provide the way for Claude to verify its work. This is of course not specific to CC Web and is solvable, but I'm not ready to pay full LLM API inference costs + a custom containerised infra provider and invest into working around their quirks.

VS Code dev container is team sharing heaven

I'd like my teammates to be able to benefit from my side quests investing in tooling. For example, I created a browser testing Skill using browser-debugger-cli (that wraps Chrome Devtools access into a CLI instead of MCP for agents) but it only helps if the scripts are zero setup, otherwise Claude Code will flail around in other people's sessions until they invest in setting up and debugging tools.

VS Code dev containers aren't designed for coding agents – the implementation prioritises convenience shortcuts rather than sandboxing – but it's a perfect starting point for reproducible dev environments. Another important piece for me was to wrap the IDE "backend" into a container, to eliminate people getting false positive linter / type errors by forgetting to install new dependencies, etc.

I'd know, I've been harping on about containerising dev environments for more than a decade! Dev containers have been around for years too, I gave them a go a few times, but never got to a point where they felt good enough. Now finally, with a bit of LLM help to keep the momentum and the kinks of the implementation ironed out throughout the years, I managed to set it up in a way that makes dev experince better rather than compromise it!

The basic structure

A minimal secured dev container setup needs three files:

.devcontainer/devcontainer.json – the main configuration that VS Code reads:

{
  "name": "Secured Dev Container",
  "dockerComposeFile": "docker-compose.yml",
  "service": "app",
  "workspaceFolder": "/app",
  "remoteUser": "vscode",
  "shutdownAction": "stopCompose",
  "remoteEnv": {
    "SSH_AUTH_SOCK": "",
    "GPG_AGENT_INFO": "",
    "BROWSER": "",
    "VSCODE_IPC_HOOK_CLI": null,
    "VSCODE_GIT_IPC_HANDLE": null,
    "GIT_ASKPASS": null,
    "VSCODE_GIT_ASKPASS_MAIN": null,
    "VSCODE_GIT_ASKPASS_NODE": null,
    "VSCODE_GIT_ASKPASS_EXTRA_ARGS": null,
    "REMOTE_CONTAINERS_IPC": null,
    "REMOTE_CONTAINERS_SOCKETS": null,
    "REMOTE_CONTAINERS_DISPLAY_SOCK": null,
    "WAYLAND_DISPLAY": null
  },
  // postStartCommand: clean up sockets created before VS Code attaches
  "postStartCommand": "find /tmp -maxdepth 2 \\( -name 'vscode-ssh-auth-*.sock' -o -name 'vscode-remote-containers-ipc-*.sock' -o -name 'vscode-remote-containers-*.js' \\) -delete 2>/dev/null || true",
  // Ongoing socket cleanup (vscode-ipc-*.sock, vscode-git-*.sock, vscode-ssh-auth-*.sock,
  // vscode-remote-containers-ipc-*.sock) is handled by a background loop in the Docker Compose
  // command – see the "Socket file deletion" section below.
  "customizations": {
    "vscode": {
      "settings": {
        "dev.containers.dockerCredentialHelper": false,
        "dev.containers.gitCredentialHelperConfigLocation": "none",
        "dev.containers.copyGitConfig": false,
        "github.gitAuthentication": false,
        "git.terminalAuthentication": false,
        "git.useIntegratedAskPass": false
      }
    }
  }
}

.devcontainer/docker-compose.yml – defines the dev container and the Docker socket proxy. Note the socket cleanup loop in the command – this is where IPC socket deletion happens (explained in the VS Code IPC hardening section below):

services:
  docker-proxy:
    image: tecnativa/docker-socket-proxy:latest
    environment:
      # Read-only operations - allowed
      CONTAINERS: 1
      IMAGES: 1
      INFO: 1
      NETWORKS: 1
      VOLUMES: 1
      # Dangerous operations - blocked
      POST: 0
      BUILD: 0
      COMMIT: 0
      EXEC: 0
      SWARM: 0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - dev

  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    volumes:
      - ..:/app:cached
    environment:
      DOCKER_HOST: tcp://docker-proxy:2375
    networks:
      - dev
    depends_on:
      - docker-proxy
    # Socket cleanup loop: deletes VS Code's bridge sockets every second, for as long as
    # the container runs – VS Code creates new ones for every terminal it opens, and
    # recreates the Dev Containers one whenever its server reconnects. Runs as a
    # child of the container's own bash process – not subject to VS Code lifecycle management.
    command: >
      bash -c '
      (while :; do
        find /tmp -maxdepth 2 \( -name "vscode-ipc-*.sock" -o -name "vscode-git-*.sock" -o -name "vscode-ssh-auth-*.sock" -o -name "vscode-remote-containers-ipc-*.sock" \) -delete 2>/dev/null;
        sleep 1;
      done) &
      sleep infinity'

networks:
  dev:
    external: true

.devcontainer/Dockerfile – crucially, without sudo, and with a shell hardening script (more on why in a moment):

FROM node:lts

# Use bash with pipefail
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

# Install useful tools (sudo intentionally omitted for security)
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    vim \
    ripgrep \
    fd-find \
    docker-cli \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID

RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME

USER $USERNAME

# Security hardening script – sourced from .bashrc before the interactive guard
# See the "VS Code IPC hardening" section for why this is needed
RUN mkdir -p /home/vscode/.config && cat << 'HARDEN' > /home/vscode/.config/security-harden.sh
unset VSCODE_IPC_HOOK_CLI VSCODE_GIT_IPC_HANDLE GIT_ASKPASS \
      VSCODE_GIT_ASKPASS_MAIN VSCODE_GIT_ASKPASS_NODE VSCODE_GIT_ASKPASS_EXTRA_ARGS \
      REMOTE_CONTAINERS_IPC REMOTE_CONTAINERS_SOCKETS REMOTE_CONTAINERS_DISPLAY_SOCK \
      WAYLAND_DISPLAY
export BROWSER= SSH_AUTH_SOCK= GPG_AGENT_INFO=
HARDEN

RUN sed -i '1i source ~/.config/security-harden.sh 2>/dev/null || true' ~/.bashrc

WORKDIR /app

CMD ["sleep", "infinity"]

The external network (dev in this example) allows your dev container to communicate with sibling services like databases or emulators that you might have running in other containers.

Securing dev containers

Right, so here's where it gets interesting. VS Code dev containers are designed to be convenient, not secure. They actively work against you by injecting various – otherwise helpful – features that happen to be security holes when you're running an autonomous coding agent.

The threat model

What are we actually protecting against?

  • Malicious npm packages – supply chain attacks that execute arbitrary code during npm install (using the postInstall hook) or at runtime
  • Prompt injection – malicious content in files, URLs, or API responses that manipulates the agent into executing harmful commands
  • AI mistakes – even without malicious intent, the agent could make errors with destructive consequences

The goal is a sandbox where the agent can work freely while limiting the blast radius of any compromise.

Docker socket proxy – preventing container escape

The most obvious attack vector is Docker itself. With direct socket access, escaping the container is trivial:

docker run -it --privileged --pid=host -v /:/host alpine chroot /host

That's complete host access in a single command. Not ideal...

The Tecnativa docker-socket-proxy intercepts Docker API calls and blocks dangerous operations. With POST: 0 and EXEC: 0, the agent can still view container logs (useful for debugging sibling services) but can't create new containers or execute commands in existing ones.

What the agent can do:

  • docker ps – list running containers
  • docker logs <container> – view container logs
  • docker inspect <container> – inspect container details

What the agent cannot do:

  • docker run – create new containers
  • docker exec – execute commands in other containers
  • docker build – build images

Why not just remove Docker access entirely? Being able to view logs of sibling containers (postgres, emulators, etc.) is genuinely useful for debugging. The proxy preserves this capability while blocking escape vectors.

Privilege escalation prevention

This one has three parts:

No sudo – don't install it. A non-root user with sudo access can escalate to root and bypass container restrictions.

$ sudo -l
bash: sudo: command not found

If you see your agent wants to use another tool, add it to the Dockerfile.

Drop all Linux capabilities – cap_drop: [ALL] in docker-compose.yml removes all kernel capabilities from the container. The container only runs Node.js, git, and bash – none of which need special capabilities at runtime. If something breaks, specific capabilities can be added back with cap_add.

Prevent new privileges – security_opt: no-new-privileges:true prevents privilege escalation via setuid/setgid binaries. Combined with removing sudo, this ensures no process in the container can gain elevated privileges.

claude-code:
  cap_drop:
    - ALL
  security_opt:
    - no-new-privileges:true

Together these strengthen the container boundary itself – even if an attacker finds a setuid binary or a way to invoke a privileged operation, the kernel will refuse.

Git push prevention – no SSH keys

Malicious code could (force-)push itself to a remote repository, establishing persistence or spreading to other systems. The fix is straightforward: don't mount SSH keys into the container. You'll also need to prevent VS Code from injecting them, see in a bit.

One credential that is unavoidable is the one for your agent – unless you're happy to log in every time – so keep it in a gitignored directory on the host:

# In .devcontainer/docker-compose.yml – no ~/.ssh mount
volumes:
  - ../.claude-docker/.claude.json:/home/vscode/.claude.json

What the agent can do:

  • git log, git status, git diff – full read access
  • git commit, git branch – local commits and branches
  • git stash, git checkout – local operations

What the agent cannot do:

  • git push – fails with an authentication error, as long as VS Code's git credential bridges are switched off too (see the settings in the IPC hardening section below) – and even then only for tools that go through the usual git config and environment, not for a process that goes looking for the sockets
  • git fetch from private repos – no credentials

2026-11-01 update: I originally only thought about SSH remotes here. With an HTTPS remote, VS Code's git extension sets GIT_ASKPASS in every terminal it opens, pointing at a helper that asks the host – your VS Code GitHub session or keychain – for credentials. So without the settings below, git push can quietly succeed using your own credentials. I found this out while building Foldyard, which caught exactly that happening.

Changes are still tracked by git, so you can review everything before pushing yourself. I personally find this an incredibly good compromise, the agent can use all the basic git functions, but unable to do destructive commands.

VS Code IPC hardening – the lesser-known attack surface

This is the sneaky one. VS Code's remote development model creates multiple Unix sockets in /tmp that enable communication between the container and host. Research by The Red Guild demonstrates these can be abused for container escape:

SocketPurposeAttack Vector
vscode-ssh-auth-*.sockSSH agent forwardingUse host SSH keys without authorisation
vscode-ipc-*.sockCLI integrationExecute commands on host via code CLI
vscode-remote-containers-ipc-*.sockHost-container RPCExtension command execution bridge, plus git and Docker credentials from the host
vscode-git-*.sockGit extension IPCGit credential access, including your VS Code GitHub session

VS Code also injects environment variables pointing to these sockets and to helper scripts that can trigger actions on the host:

VariablePoints toRisk
VSCODE_IPC_HOOK_CLIvscode-ipc-*.sockHost command execution via code CLI
VSCODE_GIT_IPC_HANDLEvscode-git-*.sock (in /tmp/user/1000/)Git credential access
GIT_ASKPASS / VSCODE_GIT_ASKPASS_*VS Code's credential helper scriptsHTTPS Git credential leakage
REMOTE_CONTAINERS_IPCvscode-remote-containers-ipc-*.sockExtension command execution
REMOTE_CONTAINERS_SOCKETSJSON array of socket pathsEnumerates multiple escape vectors
BROWSERVS Code's browser.sh helperHost-side execution via --openExternal

The remoteEnv trap

The natural first instinct is to clear these in devcontainer.json's remoteEnv:

{
  "remoteEnv": {
    "SSH_AUTH_SOCK": "",
    "BROWSER": "",
    "VSCODE_IPC_HOOK_CLI": null
  }
}

This works for some variables (SSH_AUTH_SOCK, GPG_AGENT_INFO), but VS Code re-injects its own variables (BROWSER, VSCODE_IPC_HOOK_CLI, GIT_ASKPASS, etc.) when spawning new processes. You can verify this yourself:

# Inside the container, despite remoteEnv clearing these:
$ echo $BROWSER
/vscode/vscode-server/bin/linux-x64/.../bin/helpers/browser.sh

$ echo $VSCODE_IPC_HOOK_CLI
/tmp/vscode-ipc-<uuid>.sock

So remoteEnv alone is insufficient. We need a layered approach.

The .bashrc subtlety

The obvious fix seems to be clearing these variables in .bashrc. But there's a catch: coding agents like Claude Code invoke bash as a non-interactive login shell. You can verify this:

shopt login_shell    # on – it IS a login shell
echo $-              # hmtBc – no 'i' flag, NOT interactive

For login shells, bash sources ~/.profile, which sources ~/.bashrc. But Debian's default .bashrc has an interactive guard near the top:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

This means anything after this guard is invisible to the coding agent. The fix is to source a hardening script before the guard – on line 1 of .bashrc.

Three-layer defence

Layer 1 – remoteEnv (first line of defence, partially effective):

{
  "remoteEnv": {
    "SSH_AUTH_SOCK": "",
    "GPG_AGENT_INFO": "",
    "BROWSER": "",
    "VSCODE_IPC_HOOK_CLI": null,
    "VSCODE_GIT_IPC_HANDLE": null,
    "GIT_ASKPASS": null,
    "VSCODE_GIT_ASKPASS_MAIN": null,
    "REMOTE_CONTAINERS_IPC": null,
    "REMOTE_CONTAINERS_SOCKETS": null,
    "REMOTE_CONTAINERS_DISPLAY_SOCK": null,
    "WAYLAND_DISPLAY": null
  }
}

Layer 2 – Shell hardening script (primary defence, baked into Dockerfile):

# Security hardening script – sourced from .bashrc before the interactive guard
RUN mkdir -p /home/vscode/.config && cat << 'HARDEN' > /home/vscode/.config/security-harden.sh
# VS Code IPC sockets – can execute commands on the host
unset VSCODE_IPC_HOOK_CLI

# VS Code Git extension IPC – credential access via host
unset VSCODE_GIT_IPC_HANDLE \
      GIT_ASKPASS \
      VSCODE_GIT_ASKPASS_MAIN \
      VSCODE_GIT_ASKPASS_NODE \
      VSCODE_GIT_ASKPASS_EXTRA_ARGS

# Remote Containers extension IPC – host command execution bridge
unset REMOTE_CONTAINERS_IPC \
      REMOTE_CONTAINERS_SOCKETS \
      REMOTE_CONTAINERS_DISPLAY_SOCK

# GUI forwarding (low risk but unnecessary)
unset WAYLAND_DISPLAY

# Browser helper – can trigger actions on host via --openExternal
# Set to empty rather than unset to prevent fallback to defaults
export BROWSER=

# Agent forwarding – set to empty to prevent fallback to default socket paths
export SSH_AUTH_SOCK=
export GPG_AGENT_INFO=
HARDEN

# Source it BEFORE the interactive guard in .bashrc
RUN sed -i '1i source ~/.config/security-harden.sh 2>/dev/null || true' ~/.bashrc

Layer 3 – Socket file deletion (defence in depth):

Two mechanisms handle different socket creation timings:

  • postStartCommand in devcontainer.json catches early sockets (SSH auth, remote-containers) before VS Code attaches
  • A background cleanup loop in the Docker Compose command catches IPC, git, SSH agent and Dev Containers sockets created during and after VS Code attach
{
  // In devcontainer.json – postStartCommand catches early sockets
  "postStartCommand": "find /tmp -maxdepth 2 \\( -name 'vscode-ssh-auth-*.sock' -o -name 'vscode-remote-containers-ipc-*.sock' -o -name 'vscode-remote-containers-*.js' \\) -delete 2>/dev/null || true"
}
# In docker-compose.yml – background loop catches IPC, git, SSH agent and Dev Containers sockets.
# Runs every second for as long as the container is up, because VS Code creates
# new sockets for every terminal it opens, and recreates the Dev Containers one on reconnect.
# Runs as a child of the container's own bash process, NOT a VS Code lifecycle command.
command: >
  bash -c '
  (while :; do
    find /tmp -maxdepth 2 \( -name "vscode-ipc-*.sock" -o -name "vscode-git-*.sock" -o -name "vscode-ssh-auth-*.sock" -o -name "vscode-remote-containers-ipc-*.sock" \) -delete 2>/dev/null;
    sleep 1;
  done) &
  sleep infinity'

Note -maxdepth 2 to catch sockets in /tmp/user/1000/ as well. Deleting the sockets doesn't break the IDE itself, it just keeps working without them.

2026-11-01 update: I originally ran this loop for 10 passes, 30 seconds apart, believing VS Code only created these sockets during startup and never recreated them. That's wrong: as Giles and p-buddy found in the comments below, VS Code creates a new IPC socket for every integrated terminal you open, and it forwards the SSH agent into every terminal too. So any terminal opened after the first five minutes kept its sockets. The loop now runs every second for as long as the container is up, and covers vscode-ssh-auth-*.sock as well.

2026-11-03 update: the loop now covers vscode-remote-containers-ipc-*.sock too. I used to only delete it once in postStartCommand, but reading the Dev Containers code shows it's recreated whenever the extension's server reconnects – and it turns out to hand out host credentials (more on that below). I haven't run with it in the loop for long yet, so if deleting it breaks something in your setup, I'd love to hear about it.

Why Docker Compose command instead of postAttachCommand? This was a hard-won lesson. VS Code's postAttachCommand is unreliable for background processes – VS Code appears to use cgroup-based cleanup that kills ALL processes spawned during lifecycle commands, regardless of nohup, setsid, double-fork, or any other daemonisation technique. The Docker Compose command runs as the container's own process tree, which is not subject to VS Code's lifecycle management – making it the right place for long-running background tasks.

Why three layers? Each has limitations: remoteEnv is overridden by VS Code for its own variables; the shell hardening only applies to bash processes (not direct socket access); socket deletion has a window of up to a second after each new socket appears. Together, they make standard tools and shell commands fail – but they don't stop a determined process from finding the sockets. As p-buddy's pen-testing agent showed in the comments, a long-running process (like Claude Code itself) can still carry VSCODE_IPC_HOOK_CLI in /proc/<pid>/environ, and the socket names are listed in the world-readable /proc/net/unix.

What each mitigation does:

VariableWhen ClearedTrade-off
SSH_AUTH_SOCKSSH tools can't find agentCan't use host SSH keys
GPG_AGENT_INFOGPG can't find agentCan't sign with host GPG keys
BROWSERxdg-open/open failLinks won't open in host browser
VSCODE_IPC_HOOK_CLIcode command failsCan't open files in VS Code from terminal
GIT_ASKPASS / VSCODE_GIT_ASKPASS_*Git HTTPS credential helper disabledNo HTTPS git auth (SSH already blocked)
VSCODE_GIT_IPC_HANDLEGit extension IPC disabledVS Code Git panel may lose some features
REMOTE_CONTAINERS_*Extension IPC disabledMinor feature loss in container management

You also want to disable VS Code's credential injection:

{
  "customizations": {
    "vscode": {
      "settings": {
        "dev.containers.dockerCredentialHelper": false,
        "dev.containers.gitCredentialHelperConfigLocation": "none",
        "dev.containers.copyGitConfig": false,
        "github.gitAuthentication": false,
        "git.terminalAuthentication": false,
        "git.useIntegratedAskPass": false
      }
    }
  }
}

2026-11-01 update: the two git.* settings are new. They stop VS Code's git extension putting GIT_ASKPASS into every terminal, so git push over HTTPS no longer picks up your credentials by accident. One caveat: workspace settings beat these, and .vscode/settings.json is in the repo, which the agent can edit. So it's worth checking that file hasn't turned them back on.

2026-11-03 update: I originally wrote here that the git.* settings stop the credential bridge being installed in the first place. That was wrong. On the VS Code issue about credential forwarding, laverdet showed that dockerCredentialHelper: false doesn't stop the host answering Docker credential requests – you can just curl the REMOTE_CONTAINERS_IPC socket and ask. So I went and read the source (VS Code main and the shipped Dev Containers 0.469.0 extension), and git has the same problem, twice over:

  • Dev Containers has its own git credential helper. By default it writes a credential.helper into the container's ~/.gitconfig that calls back through vscode-remote-containers-ipc-*.sock, where the host runs git credential fill against your keychain. "dev.containers.gitCredentialHelperConfigLocation": "none" stops it writing that line – but the host-side handler doesn't check the setting, and the socket gets created regardless. dockerCredentialHelper: false is the same story: it skips the wrapper script and the credsStore entry, nothing more.
  • The git extension's askpass socket is always there. The two git.* settings only decide whether GIT_ASKPASS gets injected. The extension still creates vscode-git-*.sock and answers askpass requests on it, and for github.com it asks the GitHub extension for your session – silently, if you're signed in. "github.gitAuthentication": false unregisters that, so a request falls back to a visible prompt instead.

So all these settings are still worth having – they stop ordinary tools from stumbling onto your credentials – but they only disconnect the container end. Anything that reaches one of the sockets can still ask the host directly. I've only read the code for this rather than reproducing it end to end, so if you try it and get a different result, please tell me.

The SSH agent can be dealt with at the source too. The attach forwards whatever SSH_AUTH_SOCK the VS Code process was launched with – and if it's unset, it goes looking for your real agent. So launch VS Code with an agent that holds no keys:

# Start an ssh-agent with no keys on a fixed path (if one isn't already running there)
EMPTY_AGENT="$HOME/.ssh/empty-agent.sock"
SSH_AUTH_SOCK="$EMPTY_AGENT" ssh-add -l >/dev/null 2>&1
if [ $? -eq 2 ]; then  # 2 = no agent listening; 1 would mean a running agent with no keys
  rm -f "$EMPTY_AGENT"
  ssh-agent -a "$EMPTY_AGENT" >/dev/null
fi

# Quit VS Code first – otherwise `code` just hands over to the running instance,
# which keeps the environment it was started with
SSH_AUTH_SOCK="$EMPTY_AGENT" code .

The trade-off is that terminals running on the host from that VS Code window can't use your SSH keys either. On macOS, launching VS Code from the Dock or Spotlight gives it your real agent again.

Remaining risk: every time a terminal opens, there's a window of up to a second where a targeted attack could discover and directly connect to the new sockets using VS Code's internal IPC protocol. That's a race the attacker can retry with every terminal, rather than a one-off at container startup as I originally thought. And as laverdet pointed out, it isn't even a fair race: a process watching /tmp with inotify can hardlink each socket the moment it appears, and keep using the link after the loop deletes the original. That's a big part of why I no longer see this setup as a security boundary (see the note at the top).

Triggering actions in sibling containers

With read-only Docker access, docker exec is blocked. So how does the agent interact with other services?

The answer is HTTP endpoints. If your agent needs to trigger actions in a database container or restart a service, expose an HTTP endpoint for that action. This is actually better design anyway - explicit, logged, and rate-limitable.

For example, instead of docker exec postgres pg_dump, have a small HTTP service that accepts a request and runs the backup.

Accepted risks

Not everything can be locked down without making development impractical. These are the trade-offs:

RiskImpactWhy Accepted
Network egressData exfiltration possible, and devices on your local network are reachable tooDevelopment requires internet access
Workspace write accessSource code can be modifiedEssential for development; git tracks changes
Claude credentials readableOAuth token could be stolenToken is revocable; limited blast radius
Environment variablesSecrets in .env accessibleDevelopment requires env vars, no production keys

The key insight is that these risks are containable. Network egress could be monitored, workspace changes are tracked by git, and tokens can be revoked.

Verification commands

Quick checks that security controls are working:

# Docker escape blocked
docker run alpine echo "test"  # Should fail with 403

# Sudo unavailable
sudo whoami  # Should fail

# Git push blocked – --dry-run sends nothing, but still needs credentials
git push --dry-run  # Should fail with an authentication error

# All capabilities dropped
grep 'CapEff' /proc/self/status  # Should show 0000000000000000

# No-new-privileges enforced
grep 'NoNewPrivs' /proc/self/status  # Should show 1

# VS Code escape vectors cleared
echo $VSCODE_IPC_HOOK_CLI  # Should be empty
echo $BROWSER              # Should be empty
echo $GIT_ASKPASS          # Should be empty
echo $SSH_AUTH_SOCK        # Should be empty

# No credential helper pointing back at the host
git config --show-origin --get-all credential.helper  # Should print nothing

# VS Code bridge sockets deleted (one may linger for up to a second after opening a terminal)
ls /tmp/vscode-{ipc,git,ssh-auth,remote-containers-ipc}-*.sock /tmp/user/*/vscode-{ipc,git,ssh-auth,remote-containers-ipc}-*.sock 2>/dev/null  # Should print nothing

# Read operations work
docker ps  # Should list containers
git log --oneline -5  # Should show history

Why the sandbox has to hold the whole dev environment

All this effort is about more than keeping the agent away from my keys. An LLM can't verify code "in its head", so the only way to avoid playing the slop slot machine is to give it tools to check its own work in context – type checkers, linters, integration tests against emulators, a browser. Those have to live inside the sandbox with it, which is why I went for a dev container that holds the whole dev environment rather than a sandbox around the agent alone. I wrote more about this in Feedback loop engineering.

Working code

Putting it all together, here's the (almost) full config from a Node app:

.devcontainer/devcontainer.json

The initializeCommand is a bit complex because it needs to be compatible with running multiple git worktree copies. The last bits are making sure to precreate .claude-docker/.bash_history and .claude-docker/.claude.json as Docker has the annoying habit of creating a directory on the host if nothing exists for a file host mount volume. What's cool is that this runs on the host – as opposed to command in docker-compose.yml later – so you can generate env vars dynamically.

{
  "name": "Claude Code",
  "dockerComposeFile": "docker-compose.yml",
  "service": "claude-code",
  "workspaceFolder": "/app",
  "remoteUser": "vscode",
  "shutdownAction": "stopCompose",
  "remoteEnv": {
    // First layer of defence – VS Code re-injects some of these, so the
    // security-harden.sh script sourced from .bashrc is the real safeguard.
    "SSH_AUTH_SOCK": "",
    "GPG_AGENT_INFO": "",
    "BROWSER": "",
    "VSCODE_IPC_HOOK_CLI": null,
    "VSCODE_GIT_IPC_HANDLE": null,
    "GIT_ASKPASS": null,
    "VSCODE_GIT_ASKPASS_MAIN": null,
    "VSCODE_GIT_ASKPASS_NODE": null,
    "VSCODE_GIT_ASKPASS_EXTRA_ARGS": null,
    "REMOTE_CONTAINERS_IPC": null,
    "REMOTE_CONTAINERS_SOCKETS": null,
    "REMOTE_CONTAINERS_DISPLAY_SOCK": null,
    "WAYLAND_DISPLAY": null
  },
  "initializeCommand": "bash -c 'mkdir -p .devcontainer && echo \"WORKTREE_NAME=$(basename \"$PWD\")\" > .devcontainer/.env && echo \"GIT_MAIN_REPO_PATH=$(realpath \"$(git rev-parse --git-common-dir 2>/dev/null)/..\" 2>/dev/null || echo \"$PWD\")\" >> .devcontainer/.env && echo \"LOCAL_WORKSPACE_FOLDER=$PWD\" >> .devcontainer/.env && echo \"HOST_HOME=$HOME\" >> .devcontainer/.env && echo \"HOST_UID=$(id -u)\" >> .devcontainer/.env && echo \"HOST_GID=$(id -g)\" >> .devcontainer/.env && mkdir -p .claude-docker && touch .claude-docker/.bash_history && [ -f .claude-docker/.claude.json ] || echo '{}' > .claude-docker/.claude.json'",
  // postStartCommand: clean up sockets created before VS Code attaches
  "postStartCommand": "find /tmp -maxdepth 2 \\( -name 'vscode-ssh-auth-*.sock' -o -name 'vscode-remote-containers-ipc-*.sock' -o -name 'vscode-remote-containers-*.js' \\) -delete 2>/dev/null || true",
  // Ongoing socket cleanup (vscode-ipc-*.sock, vscode-git-*.sock, vscode-ssh-auth-*.sock,
  // vscode-remote-containers-ipc-*.sock) is handled by a background loop in the Docker Compose
  // command – postAttachCommand is unreliable for background processes due to VS Code's
  // cgroup-based lifecycle cleanup.
  "customizations": {
    "vscode": {
      "settings": {
        "dev.containers.dockerCredentialHelper": false,
        "dev.containers.gitCredentialHelperConfigLocation": "none",
        "dev.containers.copyGitConfig": false,
        "github.gitAuthentication": false,
        "git.terminalAuthentication": false,
        "git.useIntegratedAskPass": false,
        "terminal.integrated.defaultProfile.linux": "bash",
        "terminal.integrated.automationProfile.linux": {
          "path": "/bin/bash"
        },
        "terminal.integrated.profiles.linux": {
          "bash": {
            "path": "/bin/bash"
          }
        }
      },
      "extensions": [
        "dbaeumer.vscode-eslint",
        "biomejs.biome",
        "prisma.prisma",
        "zenstack.zenstack",
        "johnpapa.vscode-peacock",
        "anthropic.claude-code",
        "ms-azuretools.vscode-docker"
      ]
    }
  }
}

.devcontainer/docker-compose.yml

services:
  docker-proxy:
    image: tecnativa/docker-socket-proxy:latest
    environment:
      # Read-only operations - allowed
      CONTAINERS: 1
      IMAGES: 1
      INFO: 1
      NETWORKS: 1
      VOLUMES: 1
      # Dangerous operations - blocked
      POST: 0
      BUILD: 0
      COMMIT: 0
      EXEC: 0
      SWARM: 0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - dev

  # Forwards localhost:3000-3005 inside devcontainer to the app container
  # This allows Auth0 redirects to work with dynamic port assignment
  # (Auth0 has localhost:3000-3005 registered as allowed callback URLs)
  localhost-proxy:
    image: alpine/socat
    network_mode: "service:claude-code"
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        APP_HOST="${WORKTREE_NAME:-platform-frontend-next}"
        for port in 3000 3001 3002 3003 3004 3005; do
          socat TCP-LISTEN:$$port,fork,reuseaddr TCP:$$APP_HOST:3000 &
        done
        wait
    restart: unless-stopped
    depends_on:
      - claude-code

  claude-code:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
      args:
        USER_UID: ${HOST_UID:-1000}
        USER_GID: ${HOST_GID:-1000}
    container_name: claude-code-${WORKTREE_NAME:-default}
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    volumes:
      # Workspace
      - ..:/app:cached
      # Isolated node_modules per worktree
      - node-modules:/app/node_modules
      # Git worktree support - mount main repo's .git to same absolute path
      - ${GIT_MAIN_REPO_PATH}/.git:${GIT_MAIN_REPO_PATH}/.git:cached
      # Claude config and logs
      - ${LOCAL_WORKSPACE_FOLDER}/.claude-docker/.claude.json:/home/vscode/.claude.json
      - ${LOCAL_WORKSPACE_FOLDER}/.claude-docker/.bash_history:/home/vscode/.bash_history
      # Shared pnpm store (macOS path with Linux fallback)
      - ${PNPM_STORE_PATH:-${HOST_HOME}/Library/pnpm/store}:/home/vscode/.local/share/pnpm/store:cached
      # Playwright browser cache (persists between container restarts)
      - playwright-browsers:/home/vscode/.cache/ms-playwright
    environment:
      DOCKER_HOST: tcp://docker-proxy:2375
      DATABASE_URL: postgresql://postgres:password@postgres:5432/onboarding-db
      DATABASE_HOST: postgres
      DATABASE_PORT: 5432
      BQ_EMULATOR_HOST: http://bigquery-emulator:9050
      PLAYWRIGHT_BROWSERS_PATH: /home/vscode/.cache/ms-playwright
    env_file:
      - .env
      - ../.env
    networks:
      - dev
    depends_on:
      - docker-proxy
    # These are running here instead of Dockerfile to ensure freshness and happen in the background while the IDE is already open.
    # The socket cleanup loop starts first and runs every second for as long as the container
    # is up – VS Code creates new IPC, git and SSH agent sockets for every terminal it opens,
    # and recreates the Dev Containers one whenever its server reconnects.
    # Runs as a child of the container's own bash process – not subject to VS Code's
    # cgroup-based lifecycle cleanup.
    command: >
      bash -c '(while :; do
        find /tmp -maxdepth 2 \( -name "vscode-ipc-*.sock" -o -name "vscode-git-*.sock" -o -name "vscode-ssh-auth-*.sock" -o -name "vscode-remote-containers-ipc-*.sock" \) -delete 2>/dev/null;
        sleep 1;
      done) &
      . /home/vscode/.bashrc &&
      curl -fsSL https://claude.ai/install.sh | bash &&
      pnpm config set store-dir /home/vscode/.local/share/pnpm/store &&
      pnpm install &&
      just platform-frontend playwright-ensure-browsers;
      sleep infinity'

networks:
  dev:
    external: true

volumes:
  node-modules:
    name: claude-code-${WORKTREE_NAME:-default}-node-modules
  playwright-browsers:
    name: claude-code-${WORKTREE_NAME:-default}-playwright-browsers

Dockerfile

This is based of Debian and installs Node manually to be able to track the version in .nvmrc. Note the security hardening script baked into the image – this is the primary defence against VS Code's re-injected environment variables.

FROM debian:trixie

# Use bash for the shell with pipefail
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

# Install system dependencies (sudo intentionally omitted for security)
# To get Chromium deps via Playwright you can run:
# pnpm --filter platform-frontend-next exec playwright install chromium --with-deps --dry-run
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    git \
    xz-utils \
    jq \
    vim \
    ripgrep \
    fd-find \
    htop \
    less \
    tree \
    docker-cli \
    wget \
    locales \
    just \
    unzip \
    libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 libatspi2.0-0t64 libcairo2 libcups2t64 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0t64 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 xvfb fonts-noto-color-emoji fonts-unifont libfontconfig1 libfreetype6 xfonts-scalable fonts-liberation fonts-ipafont-gothic fonts-wqy-zenhei fonts-tlwg-loma-otf fonts-freefont-ttf \
    && rm -rf /var/lib/apt/lists/*

# Generate and configure locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \
    locale-gen
ENV LANG=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8

# Create non-root user using host user ID / GID numbers
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID

RUN if getent group $USER_GID >/dev/null; then \
        useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
    else \
        groupadd --gid $USER_GID $USERNAME && \
        useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
    fi

RUN mkdir -p /app/node_modules /app/apps/platform-frontend/node_modules \
    /usr/local/lib/node_modules && chown -R $USER_UID:$USER_GID /app

# Install Node.js using the version in .nvmrc
COPY .nvmrc /tmp/.nvmrc
RUN NODE_VERSION=$(cat /tmp/.nvmrc | tr -d '[:space:]') \
    && ARCH=$(uname -m | sed 's/x86_64/x64/' | sed 's/aarch64/arm64/') \
    && curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${ARCH}.tar.xz" \
    | tar -xJ -C /usr/local --strip-components=1 \
    && rm /tmp/.nvmrc \
    && npm install -g pnpm@10.12.4

# Switch to non-root user for remaining setup
USER $USERNAME

# Set up shell environment
ENV SHELL=/bin/bash

# Security hardening: clear VS Code escape vectors injected into the container.
# This script is sourced from .bashrc BEFORE the interactive guard, so it runs
# for non-interactive login shells (which is how Claude Code invokes bash).
RUN mkdir -p /home/vscode/.config && cat << 'HARDEN' > /home/vscode/.config/security-harden.sh
# VS Code IPC sockets – can execute commands on the host
unset VSCODE_IPC_HOOK_CLI

# VS Code Git extension IPC – credential access via host
unset VSCODE_GIT_IPC_HANDLE \
      GIT_ASKPASS \
      VSCODE_GIT_ASKPASS_MAIN \
      VSCODE_GIT_ASKPASS_NODE \
      VSCODE_GIT_ASKPASS_EXTRA_ARGS

# Remote Containers extension IPC – host command execution bridge
unset REMOTE_CONTAINERS_IPC \
      REMOTE_CONTAINERS_SOCKETS \
      REMOTE_CONTAINERS_DISPLAY_SOCK

# GUI forwarding (low risk but unnecessary)
unset WAYLAND_DISPLAY

# Browser helper – can trigger actions on host via --openExternal
# Set to empty rather than unset to prevent fallback to defaults
export BROWSER=

# Agent forwarding – set to empty to prevent fallback to default socket paths
export SSH_AUTH_SOCK=
export GPG_AGENT_INFO=
HARDEN

RUN sed -i '1i source ~/.config/security-harden.sh 2>/dev/null || true' ~/.bashrc \
    && sed -i '2i export PATH="$HOME/.local/bin:$PATH"' ~/.bashrc \
    && mkdir -p /home/vscode/.local/bin /home/vscode/.cache/ms-playwright \
    /home/vscode/.local/share/pnpm/store /home/vscode/.local/share/pnpm/global

WORKDIR /app

# Note: Claude Code and dependencies are installed on container startup

CMD ["sleep", "infinity"]

.devcontainer/container-prompt.md

You might want to inject a custom prompt orienting your agent to prevent wasted tool calls. In my case this is an addendum to CLAUDE.md and I use it with: claude --append-system-prompt "$(cat .devcontainer/container-prompt.md)"

You are running inside a Docker DevContainer.

## Network - IMPORTANT
Use container hostnames, NOT localhost:
- `postgres` for PostgreSQL (port 5432)
- `bigquery-emulator` for BigQuery (port 9050)
- `fake-gcs` for GCS emulator (port 8000)
- The app container is named after the worktree directory (e.g., `platform-feature-branch`)

## Docker Access (Read-Only)
Docker access is via a socket proxy that only allows read operations:
- `docker ps` - List running containers
- `docker logs <container>` - View container logs
- `docker inspect <container>` - Inspect container details

**Blocked operations** (for security):
- `docker run` - Cannot create new containers
- `docker exec` - Cannot exec into containers
- `docker build` - Cannot build images

This prevents container escape attacks from malicious code or prompt injection.

## Git Access (Read + Local Commit Only)
- `git log`, `git status`, `git diff` - Full read access to history
- `git commit`, `git branch` - Can make local commits and branches
- `git push` - **BLOCKED** (no SSH keys mounted)

This prevents malicious code from pushing to remote repositories.

## Database
- DATABASE_URL is pre-configured to use `postgres` hostname
- BQ_EMULATOR_HOST points to the BigQuery emulator

## File System
- Project is at `/app` (same as app container)
- node_modules are in isolated Docker volumes (not synced to host)

## Privilege Restrictions
- No sudo access - cannot escalate privileges
- Non-root user (vscode) with limited capabilities

I hope this full example will help you to get going quicker, it took me a while to hand tune the small details to make sure the dev container rebuild and startup are quick.