VS Code devcontainer with an external terminal: SSH agent howto
Source: Dev.to
Why use an external terminal
I’m not a huge fan of VS Code’s internal terminal. I keep bumping into its various bugs, such as disappearing characters, Cmd‑V pasting into the wrong window, or the terminal closing when switching branches (with scm.workingSets enabled).
That said, we do use VS Code and devcontainers at work, and sometimes we need to run commands in an external terminal.
Running a command in the container from an external terminal
The following works fine for opening a shell inside the container:
CONTAINER_ID=$(docker ps --format "table {{.ID}}\t{{.Names}}" \
| grep "my-container-name" \
| awk '{print $1}')
docker exec -ti -w /workspaces/my-project "$CONTAINER_ID" /bin/zsh
The SSH‑agent problem
When using an external terminal, the SSH agent isn’t automatically available, which prevents operations like git pull. VS Code mounts the host SSH‑agent socket into the container and sets the SSH_AUTH_SOCK variable, but only for the internal terminal:
vscode ➜ /workspaces/my-project (main) $ echo $SSH_AUTH_SOCK
/tmp/vscode-ssh-auth-e85d0936-746e-465d-8382-cbf0bb69b476.sock
Work‑around: expose the SSH‑agent socket manually
The socket can be found in /tmp. By locating it and exporting SSH_AUTH_SOCK inside the docker exec command, the external terminal can use the same SSH agent:
CONTAINER_ID=$(docker ps --format "table {{.ID}}\t{{.Names}}" \
| grep "my-container-name" \
| awk '{print $1}')
docker exec -ti \
-w /workspaces/my-project \
"$CONTAINER_ID" \
sh -lc '
SOCK=$(ls /tmp/vscode-ssh-auth-*.sock 2>/dev/null | head -n1)
if [ -n "$SOCK" ]; then
export SSH_AUTH_SOCK="$SOCK"
echo "Using SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
else
echo "No VS Code SSH socket found"
fi
exec /bin/zsh
'
This is a bit hacky, but it does the job. Enjoy working from your favorite terminal!